2
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?

vishless
  • 829
  • 1
  • 5
  • 28

1 Answers1

8

&.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.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59