I currently have an array of strings. Let’s say, for example, my array
contains the following:
['one', 'two', 'three']
Each element in my array is the name of a function in my program. I
want to call the functions, using the array element. So for example,
lets say that my array is named ‘numArray’. I want to call the function
in my program named ‘one’. I am now trying numArray[0]. Is there a way
to make the numArray[0] be recognized as ‘one’ and call the function?
If my question is not clear, I can elaborate. Thanks in advance for all
help.
I currently have an array of strings. Let’s say, for example, my array
contains the following:
['one', 'two', 'three']
Each element in my array is the name of a function in my program. I want
to call the functions, using the array element.
Object#send is the method you want. It takes a method name (follows by a
list
of arguments, if there are any) as an argument and calls that method on
the
receiver.
example, lets say that my array is named ‘numArray’. I want to call
the function in my program named ‘one’. I am now trying
numArray[0]. Is there a way to make the numArray[0] be recognized
as ‘one’ and call the function? If my question is not clear, I can
elaborate. Thanks in advance for all help.
Convert the string to a symbol and send it to the appropriate object.
send( numArray[0].to_sym )
=> NoMethodError: undefined method ‘one’ for main:Object
Each element in my array is the name of a function in my program. I want
to call the functions, using the array element. So for example, lets say
that my array is named ‘numArray’. I want to call the function in my
program named ‘one’. I am now trying numArray[0]. Is there a way to make
the numArray[0] be recognized as ‘one’ and call the function? If my
question is not clear, I can elaborate. Thanks in advance for all help.
Convert the string to a symbol and send it to the appropriate object.
Convert the string to a symbol and send it to the appropriate object.
That isn’t even necessary, sending a string works just as fine.
Yeah, after the fact, I tried it like you say. For some reason, I had the
impression that strings didn’t auto-convert to symbols.
The documentation is misleading; it specifies the argument as a
symbol, but it can be either. (And I consider that a feature; I don’t
think it’s just working by chance.)
Wouldn’t you have to pass in the calling context (self from the
callers pov) if you were deffing your methods without a class? Ie
needs to k ow the object to send on, no?