我想在 Controller 中创建一个实例变量以在 View 中使用:
foo = "bar"
instance_variable_set("#{foo}", "cornholio")
在 View 中,使用@bar 以便:
@bar => "cornholio"
这会产生一个错误:'bar' is not allowed as an instance variable name
在 Rails 3.1 中工作
最佳答案
这个instance_variable_set("#{foo}", "cornholio")
需要读取instance_variable_set("@#{foo}", "cornholio")
基于 this post .刚刚在我的 irb 中为 Ruby 1.93 尝试过;该帖子来自 2009 年。
关于ruby - 如何从 Ruby on Rails 中的字符串值创建变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9612054/