Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between &.each and .each for arrays in ruby? [duplicate]

Tags:

arrays

ruby

irb(main):007:0> %w[1 2 3 4 5]&.each { |a| puts a }
1
2
3
4
5
=> ["1", "2", "3", "4", "5"]
irb(main):008:0> %w[1 2 3 4 5].each { |a| puts a }
1
2
3
4
5
=> ["1", "2", "3", "4", "5"]

Both &.each and .each seems to give the same results

ruby-doc doesn't seem to have anything regarding this functionality

What is the difference between the two?

like image 253
vishless Avatar asked Mar 04 '26 23:03

vishless


1 Answers

&.each is an operator and a method. each is only one method.

&., called “safe navigation operator”, allows to skip method call when receiver is nil. It returns nil and doesn't evaluate method's arguments if the call is skipped.

So, if the receiver is nil (which isn't the case in your example) it'll just return nil because it doesn't respond to each:

nil&.each
# nil

Otherwise, invoking any non-defined method in an object throws a NoMethodError. And is what you'll get in your second example:

nil.each
# ...
# NoMethodError (undefined method `each' for nil:NilClass)

The documentation about the safe navigation operator is in the Calling Methods documentation. While for each it's in Array.

like image 61
Sebastian Palma Avatar answered Mar 06 '26 14:03

Sebastian Palma



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!