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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

seems like a really common mistake that could be auto-corrected by prepending a @ if it didn't exist.
7

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

2 Comments

+1 for terminology! Interestingly, en.wikipedia.org/wiki/Sigil_%28magic%29 came before en.wikipedia.org/wiki/Sigil_%28computer_programming%29 when Googling.
And that's exactly the reason why one could have thought that a method like instance_variable_set takes care of adding the "@"...
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

Comments

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.