Ruby Basic

R

Raveendran .P

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 ?
 
B

Brian Candler

Jesús Gabriel y Galán said:
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
 
J

Josh Cheek

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

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 ?
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"]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,149
Messages
2,570,842
Members
47,388
Latest member
EarthaGilm

Latest Threads

Top