Search code examples
rubyinstance-variables

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


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


Solution

  • 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.