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

3

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

Heterocyclic answered 8/3, 2012 at 2:18 Comment(0)
P
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.

Political answered 8/3, 2012 at 2:29 Comment(1)
seems like a really common mistake that could be auto-corrected by prepending a @ if it didn't exist.Enterotomy
H
7

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

Hurwitz answered 8/3, 2012 at 9:58 Comment(2)
+1 for terminology! Interestingly, en.wikipedia.org/wiki/Sigil_%28magic%29 came before en.wikipedia.org/wiki/Sigil_%28computer_programming%29 when Googling.Persis
And that's exactly the reason why one could have thought that a method like instance_variable_set takes care of adding the "@"...Comras
R
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
Rovelli answered 21/5, 2020 at 23:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.