I'm an experienced developer but a Ruby newbie. I was reading this thread do..end vs curly braces for blocks in Ruby and learned some good stuff about when to use braces and when to use do .. end
blocks. One of the tips was use do .. end
when you are after side effects and {} when you are concerned about the return value. So experimenting with some of the examples in the enumerator tutorial I'm going through:
irb(main):001:0> my_array = [1, 2]
=> [1, 2]
irb(main):002:0> my_array.each {|num| num *= 2; puts "The new number is #{num}."}
The new number is 2.
The new number is 4.
=> [1, 2]
irb(main):003:0> my_array.each do |num| num *= 2; puts "The new number is #{num}." end
The new number is 2.
The new number is 4.
=> [1, 2]
Hang on. I thought the do..end
block returns an enumerator object? It looks like an array. Let's check:
irb(main):004:0> puts my_array.each {|num| num *= 2; puts "The new number is #{num}."}
The new number is 2.
The new number is 4.
1
2
=> nil
irb(main):005:0> puts my_array.each do |num| num *= 2; puts "The new number is #{num}." end
#<Enumerator:0x000055967e53ac40>
=> nil
Okay, it is an enumerator. But what happened to the output of the puts
call in the loop on line 005? The {} had the expected side effect but not the do..end
block, which seems to violate that rule of thumb.
What happened to my "The new number is #{num}."
strings?