Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

STRING PROBLEM

Status
Not open for further replies.
How can I do this:

(1)I have a variable: @a = "method_one"

(2)Then, I want to use that variable to call a method:

class A
def method_one
#code
end
end

But since the variable contents is between quotes, it doesn't work.
--------------------------------------------------------------------------
ALSO: how can you make a second text line in a window. Like if a want to make a text that reads:


T
H
I
S

Is

T
E
X
T
--------------------------------------------------------------------------
Thanks in advance
 
to call a method using a string you do:

eval(STRING)

in this case:

eval(@a)

Eval is used to make string into code. You can do alot more stuff.

eval("p 1+1")

or more complex:
eval("method_one(para1,par2)")
 
Or rather than using eval

if you want to call a method using a string or symbol call this code

method(string/symbol).call(argument list)

so for your example your code would be (method_one has no arguments)

method(@a).call

here is another example

def hi(a, b)
p "The Sum is " + (a+b).to_s
end

to call this using the above would be

method:)hi).call(4, 8) or method('hi').call(4, 8)

and this will be displayed "The Sum is 12"

what the code does is get the associated method object and then calls it
 
I think send will work better, because method is used to create an object:
Code:
method = 'string'.method('reverse')
print method.call  # gnirts

To use send:
Code:
method = 'reverse'
print 'string'.send(method)  # gnirts
 
This topic has been resolved. If kaB00M or any other users have any questions or further problems regarding this topic, please create a new thread about them.

Thank you!
 
Status
Not open for further replies.

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top