How to create a variable name from the value of a string in Ruby on Rails?

B Seven picture B Seven · Mar 8, 2012 · Viewed 14.8k times · Source

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

Answer

ScottJShea picture ScottJShea · Mar 8, 2012

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.