Any thoughts on why the following code outputs the contents of the {bracket} code but not the “do” code?
my_array = ["alpha", "beta", "gamma"]
puts my_array.collect {
|word|
word.capitalize
}
puts "======================"
puts my_array.collect do |word| word.capitalize end
puts "=========END=========="
When executed the code returns the following as the output
Alpha
Beta
Gamma
======================
#<Enumerator:0x2517ed0>
======================
Any and all help appreciated.
do ... endand{}block syntaxes have different precedence – a block defined using braces binds tighter to its caller than one usingdo ... end, which is why your first example works as intended.Edit: Elaborating a bit: When you use
puts my_array.collect {|word| word.capitalize}, you’re sending toputsthe result ofmy_array.collect {|word| word.capitalize}– the array resulting from capitalizing each item in the original array. When you useputs my_array.collect do |word| word.capitalize end, you’re passing the value ofmy_array.collect– an enumerator – toputs, and ALSO passing the block toputs. Sinceputsdoesn’tyieldto the block, you end up writing the string representation of your enumerator to$stdout, and the block never gets called. Ergo, it’s a good idea to use parenthesis when using blocks like this, unless you (and anyone you’re working on the code with!) knows exactly what’s happening.