Wednesday, April 20, 2011

do...and and {} in Ruby

http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm

Difference Between {} and do/end

As mentioned, there's one small difference between brace enclosed blocks and do/end enclosed blocks: Braces bind tighter. Watch this:

#!/usr/bin/ruby
my_array = ["alpha", "beta", "gamma"]
puts my_array.collect {
 |word|
 word.capitalize
}
puts "======================"
puts my_array.collect do
 |word|
 word.capitalize
end
[slitt@mydesk slitt]$ ./test.rb
Alpha
Beta
Gamma
======================
alpha
beta
gamma
[slitt@mydesk slitt]$

The braces bound tightly like this:

puts (my_array.collect {|word| word.capitalize})
Whereas do/end bind more loosely, like this:
puts (my_array.collect) do |word| word.capitalize} end

This issue is similar to the problem reported in http://stackoverflow.com/questions/5513531/ruby-do-end-vs-braces

No comments:

Post a Comment