-1

What I want to do is name variables dynamically like:

def instance(instance)
    @instance = instance #@instance isn't actually a variable called @instance, rather a variable called @whatever was passed as an argument
end

How can I do this?

Bobby Tables
  • 1,154
  • 4
  • 15
  • 25
  • possible duplicate of [Dynamically set local variables in Ruby](http://stackoverflow.com/questions/4963678/dynamically-set-local-variables-in-ruby) – coreyward May 05 '12 at 01:52

3 Answers3

5

Use instance_variable_set.

varname = '@foo'
value = 'bar'
self.instance_variable_set varname, value
@foo   # => "bar"

Or if you don't want the caller to have to supply the '@':

varname = 'foo'
value = 'bar'
self.instance_variable_set "@#{varname}", value
@foo   # => "bar"
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
3

If I understand correctly you want to use "instance_variable_set":

class A
end

a = A.new
a.instance_variable_set("@whatever", "foo")

a.instance_variable_get("@whatever") #=> "foo"
jordinl
  • 5,219
  • 1
  • 24
  • 20
0

You can't really.

You could play around with eval, but really, it won't be readable.

Use the correct if or use a hash instead.

# With Hash:
values = {}
a = :foo
values[a] = "bar"
values[:foo] # => "bar"

# With if
calc = "bar"
if a_is_foo
  foo = calc
else
  oof = calc
end
foo # => "bar"
Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166