30

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

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
B Seven
  • 44,484
  • 66
  • 240
  • 385

3 Answers3

39

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.

Community
  • 1
  • 1
ScottJShea
  • 7,041
  • 11
  • 44
  • 67
7

In Ruby, instance variable names always have to start with an @ sigil.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 2
    +1 for terminology! Interestingly, http://en.wikipedia.org/wiki/Sigil_%28magic%29 came before http://en.wikipedia.org/wiki/Sigil_%28computer_programming%29 when Googling. – Andrew Grimm Mar 08 '12 at 22:48
  • 2
    And that's exactly the reason why one could have thought that a method like instance_variable_set takes care of adding the "@"... – Rip-Off Jan 28 '14 at 15:24
0

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
D4v1dW3bb
  • 68
  • 6