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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With