3 ms·
Methods aren't closures in Ruby (though we have procs and lambdas for that), but you certainly can pass methods around. Methods are objects, as are unbound meth
by actsasbuffoon 12y ago
Methods aren't closures in Ruby (though we have procs and lambdas for that), but you certainly can pass methods around. Methods are objects, as are unbound methods. Both of them can be passed as arguments or returned as values. That's the definition of a first-class object.
You don't see the pattern often, as it's far less idiomatic than passing procs as a block, but you can do it.
Also, def is an expression in recent versions of Ruby. I don't remember exactly which version introduced it, but def returns the method that it created.
- mcphage 12y ago> Also, def is an expression in recent versions of Ruby. I don't remember exactly which version introduced it, but def returns the method that it created. They added that in 2.1 Well, it was always an expression... in Ruby, every statement is an expression. But it always used to return nil. Now it returns the symbol of the method name. Still not as good as returning a method object, but since you can easily get the method object from the symbol, in practice there's no difference.