From: Raveendran .P on
Hi All,

def one
puts "hi"
end

Once i call one --> i can able to get a output.


QUESTION:

I have a array method_list=["one"]

How can I convert "one" to method ?
--
Posted via http://www.ruby-forum.com/.

From: Brian Candler on
Jesús Gabriel y Galán wrote:
>> Solution:
>>
>> eval("one")
>
> I'd rather use send:
>
> irb(main):001:0> def one
> irb(main):002:1> "hi"
> irb(main):003:1> end
> => nil
> irb(main):004:0> list = %w{one}
> => ["one"]
> irb(main):005:0> send(list.first)
> => "hi"

There are some other options too.

(1) a (bound) Method object, which includes both the receiver and the
method.

class Person
def initialize(name)
@name = name
end
def greet
puts "hi I'm #{@name}"
end
end

fred = Person.new("Fred")
m = fred.method(:greet)

m.call

# compare Jesús' suggestion: fred.send(:greet)

(2) use a lambda instead of a method

m = lambda { puts "Hello" }
m.call

# This also has access to surrounding local variables (closure)

c = 0
m = lambda { c += 1; puts "Call number #{c}" }
m.call
m.call
m.call
--
Posted via http://www.ruby-forum.com/.

From: Josh Cheek on
[Note: parts of this message were removed to make it a legal post.]

On Mon, Jun 21, 2010 at 5:52 AM, Raveendran .P <jazzezravi(a)gmail.com> wrote:

> Hi All,
>
> def one
> puts "hi"
> end
>
> Once i call one --> i can able to get a output.
>
>
> QUESTION:
>
> I have a array method_list=["one"]
>
> How can I convert "one" to method ?
> --
> Posted via http://www.ruby-forum.com/.
>
>
In general, you can convert a string / symbol to the method it is maning by
using the method "method"
http://ruby-doc.org/core/classes/Object.html#M000336


def one() "hi" end
def two() "hello" end
def three() "hola" end

method_names = private_methods(false).reject { |name| name.size > 5 }
method_names # => ["three", "two", "one"]

method_list = method_names.map { |name| method name }
method_list # => [#<Method: Object#three>, #<Method: Object#two>, #<Method:
Object#one>]

method_results = method_list.map { |meth| meth.call }
method_results # => ["hola", "hello", "hi"]

From: Raveendran .P on
Hi Josh,Brain and Galan,

Thanks for your help.


Regards
Raveendran P
http://raveendran.wordpress.com
--
Posted via http://www.ruby-forum.com/.