Using string variable to call a method

  • Thread starter Bryan Richardson
  • Start date
B

Bryan Richardson

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

Hello all,

How can I use a string variable as part of a method name I'm calling? For
example say I want to call the method say_hello using the following:

def say_hello
puts "Hello!"
end

str = "hello"

say_????

Thanks in advance!! -- BTR
 
S

Stefano Crocco

Alle luned=EC 7 gennaio 2008, Bryan Richardson ha scritto:
Hello all,

How can I use a string variable as part of a method name I'm calling? For
example say I want to call the method say_hello using the following:

def say_hello
puts "Hello!"
end

str =3D "hello"

say_????

Thanks in advance!! -- BTR

send "say_#{str}"

Stefano
 
D

Daniel Finnie

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

In general, the send method is preferred over evalling a string when
possible.

In addition to send "say_#{str}", you can do method("say_#{str}".to_sym)
call.

Dan
 
B

Bryan Richardson

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

Along these same lines, is it possible to do a require and include
dynamically, getting the name of the file to require and module to include
from a string?
 
J

Jason Roelofs

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

require is obvious, the method takes a string already.

Including a module, I think you can do:

ClassName.send:)include, Module.const_get("ModuleName"))

or if you're working with an instance variable, replace :include with
:extend.

Jason
 
B

Bryan Richardson

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

send :include, Module.const_get(ARGV[1]) worked. Thanks!!
 

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
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top