[Ruby] Easy to use array.map(&:method)

less than 1 minute read

Easy to use #array.map(&:method)


Suppose you have the following formula. Convert each element to uppercase in the block and store it in array.

['a','b','c'].map{|s| s.upcase }#=> ["A", "B", "C"]

Easy using ##array.map(&:method) You can simplify the above example by using array.map(&:method).

['a','b','c'].map(&:upcase) # => ["A", "B", "C"]

Applicable condition

  1. Only one block argument
  2. The method called in the block has no arguments
  3. In the block, there is no processing other than calling the method for the block argument

Tags: ,