consider this, works fine:
:>.to_proc.curry(2)[9][8] #=> true, because 9 > 8
however, though >
binary operator, above won't work without arity specified:
:>.to_proc.curry[9][8] #=> argumenterror: wrong number of arguments (0 1)
why aren't 2 equivalent?
note: want create intermediate curried function 1 arg supplied, , then call call 2nd arg.
curry has know arity of proc passed in, right?
:<.to_proc.arity # => -1
negative values arity
confusing, mean 'variable number of arguments' 1 way or another.
compare to:
less_than = lambda {|a, b| < b} less_than.arity # => 2
when create lambda saying takes 2 arguments, knows takes 2 arguments, , work fine style of calling #curry.
less_than.curry[9][8] # => false, no problem!
but when use symbol #to_proc trick, it's got symbol go on, has no idea how many arguments takes. while don't think <
ordinary method in ruby, think you're right neccessarily takes 2 args, symbol#to_proc thing general purpose method works on method name, has no idea how many args method should take, defines proc variable arguments.
i don't read c enough follow mri implementation, assume symbol#to_proc defines proc variable arguments. more typical use of symbol#to_proc, of course, no-argument methods. can instance if want:
hello_proc = :hello.to_proc class someclass def hello(name = nil) puts "hello, #{name}!" end end obj = someclass.new obj.hello #=> "hello, !" obj.hello("jrochkind") #=> "hello, jrochkind!" obj.hello("jrochkind", "another") # => argumenterror: wrong number of arguments calling `hello` (2 1) hello_proc.call(obj) # => "hello, !" hello_proc.call(obj, "jrochkind") # => "hello, jrochkind!" hello_proc.call(obj, "jrochkind", "another") # => argumenterror: wrong number of arguments calling `hello` (2 1) hello_proc.call("some string") # => nomethoderror: undefined method `hello' "some string":string
note did hello_proc = :hello.to_proc
before defined someclass
. symbol#to_proc mechanism creates variable arity proc, knows nothing how or or on class called, creates proc can called on class @ all, , can used number of arguments.
if were defined in ruby instead of c, this:
class symbol def to_proc method_name = self proc {|receiver, *other_args| receiver.send(method_name, *other_args) } end end
Comments
Post a Comment