Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 595
B Seven Avatar asked Mar 08 '12 02:03

B Seven


People also ask

How do you use a string as the name of a variable?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.

How do you create variable names in Ruby?

Variable names in Ruby can be created from alphanumeric characters and the underscore _ character. A variable cannot begin with a number. This makes it easier for the interpreter to distinguish a literal number from a variable. Variable names cannot begin with a capital letter.

How do you pass a string in Ruby?

Ruby is strictly pass-by-value, always. There is no pass-by-reference in Ruby, ever. The simple explanation for why your code snippet doesn't show the result you would expect for pass-by-reference is that Ruby isn't pass-by-reference.


1 Answers

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.

like image 115
ScottJShea Avatar answered Sep 19 '22 15:09

ScottJShea