I noticed following difference in behavior when I use map, select, and other Enumerable methods.
Let's assume we have a hash like below:
h = {a: 1}
Below code prints the output of select as expected.
p h.select { |k, v| true }
#=> {:a=>1}
However, below code shows that output is an Enumerator, even when a block has been provided.
p h.select do |k, v|
true
end
#=> #<Enumerator: {:a=>1}:select>
Any idea why this difference of behavior? I run into this issue often as I keep using inspect p while working, and this behavior derails my thought process quite often.
Operator precedence matters.
p h.select do |k, v| true end
is in fact executed as:
(p h.select) do |k, v| true end
while
p h.select { |k, v| true }
is treated as:
p (h.select { |k, v| true })
Enumerable#select, called without a block, returns an enumerator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With