Forum: Ruby Is it possible to bind a parameter to a (unary) Proc object?

0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2016-12-06 13:41
(Note: Having received no responses yet at this forum, I crossposted the
question at
http://stackoverflow.com/questions/41116975/is-it-...)

Here is a (very) simplified, working version of what I have:

class S
  def initialize(s); @ms = s; end
  def s_method1(i); puts "s_method1 #{i} #{@ms}"; end
  def s_method2; puts "s_method2 #{@ms}"; end
end

class T
  def initialize(s, choice=nil)
    @s = S.new(s)
    @pobj = choice ? lambda { @s.s_method1(choice) } :
@s.method(:s_method2)
  end
  def invoke
    @pobj.call
  end
end


In this example, depending on how T is constructed, T#invoke calls
either S#s_method1 or S#S_method2, but in the case of calling
S#s_method1, the parameter to s_method1 is already fixed at creation
time of the T object. Hence, the following two lines,

T.new('no arguments').invoke
T.new('one argument', 12345).invoke

produce the output

    s_method2 no arguments
    s_method1 12345 one argument

which is exactly what I want to have.

Now to my problem:

In the case, where choice is nil, i.e. where I want to invoke the
parameterless method s_method2, I can get my callable object in an
elegant way by

   @s.method(:s_method2)

In the case where choice is non-nil, I had to construct a Proc object
with lambda. This not only looks clumsy, but also makes me feel a bit
uncomfortable. We have a closure here, which is connected to the
environment inside the initialize method, and I'm not sure whether this
could cause trouble by causing memory leaks in some circumstances.

Is there an easy way to simply bind a method object (in this case
@s.method(:s_method1) to a fixed argument?

My first idea was to use

  @s.method(:s_method1).curry[choice]

but this would not return a callable Proc object, but actually execute
s_method1 already (this is not a bug, but documented behaviour).

Any other ideas of how my goal could be achieved?
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.