I have a method by the name methodA. I want to access this method like
this
a = ‘methodA’
eval(a)
But how do I know if the variable a actually holds the name of a
defined method? An exception is raised if I try to run eval(a) with an
incorrect method name, but I need to know this before I call eval(a).
How do I do that?
I found this solution:
def method?(arg)
begin
method(a)
rescue
nil
end
end
which does work, but why is this function “method?” not already in the
Ruby language then?
Alle Saturday 13 September 2008, Fredrik ha scritto:
which does work, but why is this function “method?” not already in the
Ruby language then?
In my opinion, for two reasons:
the name is misleading. Methods ending in ? usually are method which
only
answer a Yes/No question, without taking any action. The method you
propose,
instead, perform an action and doesn’t give an answer to a question. If
I were
a user seeing a method called ‘method?’, I’d think it’s a synonym for
respond_to?, or similar to it.
This functionality isn’t needed very often, and it’s very easy to
write
your own method if you need it, as you have done.
I will open my Ruby book and look into that send thing…
send is quite simple actually:
send(“foo”) is the same as foo
send(“foo”, bar) is the same as foo(bar)
object.send(“foo”, bar) is the same as object.foo(bar)
That’s basically it.
respond_to? returns false for private methods. If you define a method
outside
of a class/module, it’s a private instance method of Object by default,
except
when you define it in irb in which case it will be public for whatever
reason.
I will open my Ruby book and look into that send thing…
send is quite simple actually:
send(“foo”) is the same as foo
send(“foo”, bar) is the same as foo(bar)
object.send(“foo”, bar) is the same as object.foo(bar)
That’s basically it.
Almost
c.send(“x”)
=> nil
c.x
NoMethodError: private method `x’ called for #<C:0x3c95ec>
David
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.