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 ?
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 ?
Raveendran .P wrote:
Hi All,
def one
puts “hi”
endOnce 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 ?
Tried and Got Solution
Solution:
eval(“one”)
Thanks
On Mon, Jun 21, 2010 at 1:00 PM, Raveendran .P [email protected]
wrote:
QUESTION:
I have a array method_list=[“one”]
How can I convert “one” to method ?
Tried and Got SolutionSolution:
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”
Jesus.
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
(2) use a lambda instead of a method
m = lambda { puts “Hello” }
m.call
c = 0
m = lambda { c += 1; puts “Call number #{c}” }
m.call
m.call
m.call
Hi Josh,Brain and Galan,
Thanks for your help.
Regards
Raveendran P
On Mon, Jun 21, 2010 at 5:52 AM, Raveendran .P [email protected]
wrote:
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”]
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs