ironsand ironsand - 6 months ago 14
Ruby Question

How to use &proc argument inside method

Array#max_by
returns only a single value, but I want to have all values that have the max value.

hashes = [{a: 1, b:2}, {a:2, b:3}, {a:1, b:3}]
max = hashes.map{|h| h[:b]}.max
hashes.select{|h| h[:b] == max}
# => [{a: 2, b: 3}, {a: 1, b: 3}]


This code works fine, and I want to add it to
Array
class.

class Array
def max_values_by(&proc)
max = map(&proc).max
# I don't know how to use `select` here.
end
end


How to access the value of the
&proc
argument?

Answer

Use the proc in the block passed to select by calling it with call:

class Array
  def max_values_by(&proc)
    max = map(&proc).max
    select { |h| proc.call(h) == max }
  end
end
hashes.max_values_by { |h| h[:b] }
=> [{a: 2, b: 3}, {a: 1, b: 3}]