mariko
March 4, 2008, 12:03am
1
I’d like to change a string, for example, “something” and turn it into
an object reference. For example:
I have string “something,” now I’d like to take that and turn it into
something = “some other string”
Is this possible? Thanks in advance for any help.
mariko
March 4, 2008, 12:20am
2
On 3/3/08, Mariko C. [email protected] wrote:
I’d like to change a string, for example, “something” and turn it into
an object reference. For example:
I have string “something,” now I’d like to take that and turn it into
something = “some other string”
Is this possible? Thanks in advance for any help.
I’m not sure how you’d do it otherwise, but using Rails I do it like
this:
c = “foo”.singularize.camelize.constantize
bar = c.new
mariko
March 4, 2008, 1:43am
3
Mariko C. wrote:
I’d like to change a string, for example, “something” and turn it into
an object reference. For example:
I have string “something,” now I’d like to take that and turn it into
something = “some other string”
Is this possible? Thanks in advance for any help.
Meta-programming to the rescue!
#!/usr/bin/env ruby
a = “aString”
eval(a + " = 5")
puts aString
mariko
March 4, 2008, 8:50am
4
Joshua B. wrote:
Meta-programming to the rescue!
#!/usr/bin/env ruby
a = “aString”
eval(a + " = 5")
puts aString
Hi Joshua. I tried this through irb and it works fine, but it gives me
an “undefined local variable” error through Ruby on Rails. Any idea how
to get this to work?
mariko
March 4, 2008, 1:46am
5
On 3/3/08, Mariko C. [email protected] wrote:
I’d like to change a string, for example, “something” and turn it into
an object reference. For example:
I have string “something,” now I’d like to take that and turn it into
something = “some other string”
Is this possible? Thanks in advance for any help.
If I understand you properly, you have the name of a variable in a
string, and you want to use that string to fetch the actual variable
by that name.
What you want is Object#instance_variable_get:
@a = “@b ”
@b = [“this is a test”]
instance_variable_get(@a )
=> [“this is a test”]
Note that the @ is important. You can always prepend it as needed:
instance_variable_get(“@” + @a )
Christopher
mariko
March 4, 2008, 10:22am
6
Hi,
On Tue, Mar 4, 2008 at 6:50 PM, Mariko C. [email protected]
wrote:
Hi Joshua. I tried this through irb and it works fine, but it gives me
an “undefined local variable” error through Ruby on Rails. Any idea how
to get this to work?
Can you show us the code? Possibly a variable name was misspelled.
Arlen