在方法名称在另一个变量中的变量上调用方法 [英] Call a method on a variable where the method name is in another variable

查看:39
本文介绍了在方法名称在另一个变量中的变量上调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<% @labels.each do |label| %>
    <input type="text" name="<%=label.name%>" value="<%=@car.(label.related_to) %>" class="big-font" style="width: <%=label.width%>px; top: <%=label.y_coor%>px; left: <%=label.x_coor%>px;" /> 
<% end %>

大家好,我是 Rails 新手,所以这个问题应该很容易回答.

Hello guys, I'm new to rails so this should be a fairly easy question to answer.

问题在这里:<%=@car.(label.related_to) %>.

label.related_to 保存字符串make".我试图让它做到这一点:@car.make

label.related_to holds the string "make". I'm trying to get it to do this pretty much: @car.make

有什么想法吗?

谢谢,阿兰

推荐答案

使用 send 向对象发送消息:

Use send to send a message to an object:

@car.send(label.related_to)

如果 label.related_to 有可能不是对象的有效方法,您可能希望准备捕获 NoMethodError

If there is any chance of label.related_to not being a valid method for the object, you'll probably want to be prepared to catch the NoMethodError

这篇关于在方法名称在另一个变量中的变量上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆