I need to dynamically call a class method (i.e., unless there is some
other way, the name of the class method should be contained in a
variable). I have come up with the way illustrated in the example shown
below. The program is in the file, 'test1'. The relevant method is in
the file, 'Test1a.rb'. I use 'eval' which (I believe) is frowned upon.
Does anyone have a better way of accomplishing this objective? Thanks
for any input.
... doug
$ ls
test1 Test1a.rb
$ cat Test1a.rb
class Test1a
def Test1a.howdy()
return 'Hello, world!'
end
end
$ cat test1
#!/usr/bin/ruby
require './Test1a.rb'
myvar='howdy'
puts(eval("Test1a.#{myvar}()"))
$ ./test1
Hello, world!
$
···
--
Posted via http://www.ruby-forum.com/.
Use send:
lizzy:/tmp% cat Test1a.rb
class Test1a
def Test1a.howdy
return 'Hello, world!'
end
end
lizzy:/tmp% cat test1
#!/usr/bin/env ruby
require_relative 'Test1a'
myvar = 'howdy'
puts Test1a.send myvar
lizzy:/tmp% ./test1
Hello, world!
lizzy:/tmp%
···
--
Jos Backus
jos at catnook.com
Use #send, e.g.
myvar = "howdy"
Test1a.send(myvar)
···
On Fri, Jan 20, 2012 at 1:15 AM, Doug Jolley <ddjolley@gmail.com> wrote:
I need to dynamically call a class method (i.e., unless there is some
other way, the name of the class method should be contained in a
variable). I have come up with the way illustrated in the example shown
below. The program is in the file, 'test1'. The relevant method is in
the file, 'Test1a.rb'. I use 'eval' which (I believe) is frowned upon.
Does anyone have a better way of accomplishing this objective? Thanks
for any input.
\.\.\. doug
$ ls
test1 Test1a.rb
$ cat Test1a.rb
class Test1a
def Test1a.howdy()
return 'Hello, world!'
end
end
$ cat test1
#!/usr/bin/ruby
require './Test1a.rb'
myvar='howdy'
puts(eval("Test1a.#{myvar}()"))
$ ./test1
Hello, world!
$
--
Thanks so much for turning me on to 'send'.
I figured out that a comma-delimited list of any needed method arguments
may be appended to the variable containing the method name. I also
found 'respond_to?' which allows me to test whether a particular method
exists. Armed with this new knowledge, I think that I will be able to
get where I want to go.
Thanks for all the help.
... doug
···
--
Posted via http://www.ruby-forum.com/.