如何从Ruby on Rails中的字符串值创建变量名?

时间:2021-11-07 23:41:37

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以便:

@bar => "cornholio"

This generates an error: 'bar' is not allowed as an instance variable name

这会产生错误:'bar'不允许作为实例变量名称

Working in Rails 3.1

在Rails中工作3.1

2 个解决方案

#1


35  

This instance_variable_set("#{foo}", "cornholio") needs to read instance_variable_set("@#{foo}", "cornholio")

这个instance_variable_set(“#{foo}”,“cornholio”)需要读取instance_variable_set(“@#{foo}”,“cornholio”)

Based on this post. Just tried it in my irb for Ruby 1.93; the post is from 2009.

基于这篇文章。刚刚在我的irb中尝试过Ruby 1.93;这篇文章是2009年的。

#2


7  

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

在Ruby中,实例变量名称始终必须以@sigil开头。

#1


35  

This instance_variable_set("#{foo}", "cornholio") needs to read instance_variable_set("@#{foo}", "cornholio")

这个instance_variable_set(“#{foo}”,“cornholio”)需要读取instance_variable_set(“@#{foo}”,“cornholio”)

Based on this post. Just tried it in my irb for Ruby 1.93; the post is from 2009.

基于这篇文章。刚刚在我的irb中尝试过Ruby 1.93;这篇文章是2009年的。

#2


7  

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

在Ruby中,实例变量名称始终必须以@sigil开头。