Ruby parens-free function calls [was Re: Accessing parent objects]

Rick Johnson rantingrickjohnson at gmail.com
Tue Mar 27 08:00:30 EDT 2018


On Tuesday, March 27, 2018 at 1:55:01 AM UTC-5, Gregory Ewing wrote:
> Chris Angelico wrote:
> > Question: How do you get a reference to a Ruby function? Or are they
> > not first-class objects?
>> They're not first-class. So, you can't.

If Chris means: "how do you get a reference to a Ruby
function object", then yes, it _is_ possible! Consider the
following:
 ## Ruby 1.9 ##
 rb> def print_name(name); puts "Your name is #{name.inspect}"; end
 rb> print_name("Chris")
 "Chris"
In this case, since the function `print-name` was defined
outside of an class definition, Ruby will add the function
as a method of `Object` (Ruby is more purist about OOP than
Python). So, to get a reference to the function object
(which is now a method of `Object`!), all we need to do is
call a method named "method" ("gigity") and pass it the name
of the method as a string:
 rb> Object.method("print_name")
 #<Method: Class(Object)#print_name>
 rb> Object.method("print_name").call("Meathead")
 Your name is "Meathead"
PS: Greg, please inform Chris that Google is his friend. ;-)


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /