String to Object name?

M

Mariko C.

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.
 
G

Greg Donald

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
 
J

Joshua Ballanco

Mariko said:
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
 
C

Christopher Swasey

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
 
M

Mariko C.

Joshua said:
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?
 
A

Arlen Cuss

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

Hi,

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
 

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

No members online now.

Forum statistics

Threads
473,813
Messages
2,569,696
Members
45,479
Latest member
QFZErin313

Latest Threads

Top