Reputation: 2411
A ruby method is an Object
. For example:
def method
'does something'
end
method.is_a? Object #=> true
def method; end
method.is_a? Object #=> true
Why is a method a Object
?
Upvotes: 0
Views: 551
Reputation: 6635
Like Ilya Konyukhov wrote, calling method.is_a?(Object)
checks the return value of calling method
, which would be "does something"
and nil
respectively - both of which are Object
s.
Rubys methods are not objects per se but you can get an object representation of them using the Object#method
method.
The funny part of your specific example is, that you unfortunately named your test method "method", thus overwriting your self
s method method
.
Take a look at this example, where I named my method "test" instead:
def test; end
test.class.name => "NilClass"
method(:test).class.name => "Method"
As you see, test
is calling the method and everything after (e.g. is_a?
or class.name
) is called on the return value.
method(:test)
, however, returns an object representation (of class Method
) of the method itself.
Upvotes: 2
Reputation: 80075
"Ruby' s methods are not objects in the way that strings, numbers and arrays are" (The Ruby Programming Language, Flanagan and Matsumoto, page 176). OP' s method name "method" is unfortunate; it makes it almost impossible to explain anything. If you need to treat a method as an object, there is the method method, which results in an instance of Class Method.
Upvotes: 1
Reputation: 2791
method.is_a?(Object)
can be rewritten as
res = method
res.is_a?(Object)
So you call a method and ask if its result -- a String
instance -- is an Object
. For sure it is.
It can be easily verified with:
method.is_a?(String) # also returns true
Update:
If you want to check if a method itself an Object
or not, you can do it with this code snippet:
def method2
"some string"
end
method2_ref = Object.method(:method2) # #<Method: Object.method2>
method2_ref.is_a? Object # true
method2_ref.is_a? String # false
As it is mentioned in the comments, Method
instance is also an Object
.
Upvotes: 2