Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Proc with Parameter

Tags:

ruby

lambda

proc

I'm trying to send a parameter to a Ruby proc

p1 = [54, 21, 45, 76, 12, 11, 67, 5]

qualify = proc { |age, other| age > other }

puts p1.select(&qualify(30))

This is the error I get:

undefined method `qualify' for main:Object

age comes from the iteration of the array, and I want to have that last parameter (30) to get into the proc.

Is a proc the right tool to be using for this? I'm new to proc. I'm unclear how to get that parameter in there.

like image 716
Rich_F Avatar asked Sep 01 '25 03:09

Rich_F


1 Answers

In order to use qualify in as select predicate, you need to reduce its arity (number of accepted arguments) through partial application. In other words - you need a new proc that would have other set to 30. It can be done with Method#curry, but it requires changing order of parameters:

qualify = proc { |other, age| age > other }
qualify.curry.call(30).call(10)
# => false
qualify.curry.call(30).call(40)
#=> true

I order to be able to pass this proc to select using &, you need to assign it so that it's available in the main object, e.g. by assigning it to an instance variable:

@qualify_30 = qualify.curry.call(30)

Now you can call:

p1.select{ |age| @qualify_30.call(age)  }
# => [54, 45, 76, 67]

or:

p1.select(&@qualify_30)
# => [54, 45, 76, 67]

or inline:

p1.select(&qualify.curry.call(30))
# => [54, 45, 76, 67]
like image 55
mrzasa Avatar answered Sep 02 '25 15:09

mrzasa