I'm going through a tutorial on Ruby that explains the neat construction the select
method provides. As per that, the three print statements in the following code (filtering out even numbers) should produce an identical output:
numbers = (1..20).to_a
p numbers.select(&:even?)
p numbers.select { |x| x.even? }
p numbers.select do |x| x.even? end
When I run it, though, I get:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
#<Enumerator: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]:select>
Clearly, the third statement is off, even though it's impossible to tell why. It's just the curly braces replaced with the do-end
block so it shouldn't change anything.
I'm on Ruby 2.5 so I guess either the tutorial was running some other version and something has changed? Or maybe there's some subtlety here that I'm not able to put my finger on.