First tricks today, here is an easy one :
If you are using Active Support (shipped with Rails), or a ruby version superior or equal to 1.8.7, you can use the symbol proc shortcut :
Here is the standard way declaring a block :
>> ['a', 'b', 'c'].collect {|letter| letter.capitalize}
=> ["A", "B", "C"]
=> ["A", "B", "C"]
Here is the handy method :
>> ['a', 'b', 'c'].collect(&:capitalize)
=> ["A", "B", "C"]
=> ["A", "B", "C"]
But, keep in mind that the shortcut method is a little bit slower in term of performance than the normal way cause it creates a new Proc on each call !
Benchmark :
t = Benchmark.realtime do
(['a'] * 1000000).collect(&:to_s)
end
puts "Time using to_proc: #{t}"
t = Benchmark.realtime do
(['a'] * 1000000).collect do |e|
e.to_s
end
end
puts "Time using normal block: #{t}"
# Time using to_proc: 0.631899118423462
# Time using normal block: 0.246822834014893
# Results are the same if you test the normal block first
(['a'] * 1000000).collect(&:to_s)
end
puts "Time using to_proc: #{t}"
t = Benchmark.realtime do
(['a'] * 1000000).collect do |e|
e.to_s
end
end
puts "Time using normal block: #{t}"
# Time using to_proc: 0.631899118423462
# Time using normal block: 0.246822834014893
# Results are the same if you test the normal block first

What a trick !