Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behavior with map, select, etc. when using do...end blocks [duplicate]

Tags:

ruby

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.

like image 918
Wand Maker Avatar asked Nov 29 '25 03:11

Wand Maker


1 Answers

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.

like image 130
Aleksei Matiushkin Avatar answered Dec 02 '25 05:12

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!