2

我有一个 User 模型,其中包含许多非常相似的属性,我想列出这些属性,而无需单独输入每个属性。

所以,而不是:

"eye color: #{@user.his_eye_color}"
"hair color: #{@user.his_hair_color}"
"height: #{@user.his_height}"
"weight: #{@user.his_weight}"
...

"eye color: #{@user.her_eye_color}"
"hair color: #{@user.her_hair_color}"
"height: #{@user.her_height}"
"weight: #{@user.her_weight}"
...

我想做一个块或其他东西(Proc?Lambda?仍然不清楚那些是什么......):

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.her_(stat.underscore)}"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.his_(stat.underscore)}"
end

我知道我刚刚在上面写的很神秘,很神奇,而且完全完全错误(@user.his_(stat.underscore)部分),但是我能做这样的事情吗?我基本上需要动态调用我的模型的属性,但我不确定如何做到这一点......

任何帮助将非常感激!

4

2 回答 2

5
['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"her_#{stat.tr(" ","_")}") }"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"his_#{stat.tr(" ","_")}") }"
end

这应该有效。您始终可以使用send调用对象上的方法,并动态生成该方法名称作为字符串

于 2010-02-11T16:10:06.993 回答
2

如果您在 Rails 中使用 ActiveRecord,您还可以使用 Object#[] 方法动态获取属性值

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user[ "her_#{ stat.underscore }"]}"
end
于 2010-02-11T16:14:18.637 回答