Mariko_C
(Mariko C.)
3 March 2008 23:03
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.
···
--
Posted via http://www.ruby-forum.com/ .
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
···
On 3/3/08, Mariko C. <lessthaneloquent@yahoo.com> 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.
--
Greg Donald
http://destiney.com/
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
···
--
Posted via http://www.ruby-forum.com/\ .
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
···
On 3/3/08, Mariko C. <lessthaneloquent@yahoo.com> 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.
Mariko_C
(Mariko C.)
4 March 2008 07:50
5
Joshua Ballanco 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?
···
--
Posted via http://www.ruby-forum.com/\ .