Reputation: 45943
I want to create an instance variable in a controller to be used in the view:
foo = "bar"
instance_variable_set("#{foo}", "cornholio")
In the view, use @bar so that:
@bar => "cornholio"
This generates an error: 'bar' is not allowed as an instance variable name
Working in Rails 3.1
Upvotes: 30
Views: 15568
Reputation: 68
I was looking for the answer for the same question but with an other thought. Because other people might ending up here looking for my answer here my question and solution:
I want to cal t(key, interpolation_var: value) in a method. where interpolation _var: is different per translation. solution(I have removed all non important information so only the solution to the problem is available. that's why the method looks unusefull :) ):
def some_function(key, interpolation_var, value)
t(key, :#{interpolation_var} => value)
end
Upvotes: 0
Reputation: 369458
In Ruby, instance variable names always have to start with an @
sigil.
Upvotes: 7
Reputation: 7111
This instance_variable_set("#{foo}", "cornholio")
needs to read instance_variable_set("@#{foo}", "cornholio")
Based on this post. Just tried it in my irb for Ruby 1.93; the post is from 2009.
Upvotes: 39