3

Is there a nicer way to write something like:

array.each { |item| method(item) }

I'm aware of array.each(&:method) which calls the method on each item, but is there a similar shorthand for calling a method with each item?

Dom Christie
  • 4,152
  • 3
  • 23
  • 31
  • So the receiver is `self` (given in the context) for each element? – sawa Sep 03 '18 at 11:25
  • 1
    Check https://andrewjgrimm.wordpress.com/2011/10/03/in-ruby-method-passes-you/. – yzalavin Sep 03 '18 at 11:28
  • 1
    `array.each(&method(:method))` should work, where `:method` is the name of the method you'd like to invoke and `method` is the [`method`](http://ruby-doc.org/core-2.5.1/Object.html#method-i-method) method (which returns a `Method` object for the given method name) ;-) – Stefan Sep 03 '18 at 11:33
  • @stefan if you'd like to convert that to an answer, I'd gladly accept and upvote. Thanks! – Dom Christie Sep 03 '18 at 11:37
  • 1
    @DomChristie I'm pretty sure this has been asked before, so maybe we can close it as a duplicate ... – Stefan Sep 03 '18 at 11:38
  • 3
    Great! I found this: https://stackoverflow.com/questions/18816654/is-there-a-more-concise-way-to-call-an-outside-method-on-a-map-in-ruby/18816670#18816670 Much easy to search for when you've got the answer! :) – Dom Christie Sep 03 '18 at 11:49

0 Answers0