-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?

1

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

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"

3 Comments

how? what exactly do you mean?
He means: var = :a; hash = { var => 'foo' }; hash[var] = 'bar'; hash[var];
I would never suggest the use of eval for this. It's a design flaw and eval is dangerous in the wrong hands ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.