I'm a little confused about this behavior from the ruby (1.9) interpreter
class Foo
def pub
private_thing
end
private
def private_thing
puts "private touch"
end
end
x = Foo.new
x.pub
private touch
=> nil
so far so good.
x.private_thing
NoMethodError: private method `private_thing' called for #<Foo:0xb76abd34>
from (irb):25
from :0
still ok. that's what I expected
but why is this empty?
x.methods(false)
=> []
while this gives me what I was expecting?
Foo.instance_methods(false)
=> ["pub"]
The first method to find the methods is to use the dir() function. This function takes an object as an argument and returns a list of attributes and methods of that object. From the output, we can observe that it has returned all of the methods of the object.
In Ruby, methods are not objects.
There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.
Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false .
Indeed, the "methods" method seems to have disappeared. You should use public_instance_methods instead.
To explain why that x.methods(false)
is behaving that way, look back at ruby 1.9.1 docs http://www.ruby-doc.org/core-1.9.1/Object.html#method-i-methods. If you see the source code if you pass in a parameter it behaves as singleton_methods, which is what you're seing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With