Call a method on a variable where the method name is in another variable

点点圈 提交于 2020-01-04 05:44:54

问题


<% @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 %>

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

The issue is here: <%=@car.(label.related_to) %>.

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

Any idea guys?

Thanks, Alain


回答1:


Use send to send a message to an object:

@car.send(label.related_to)

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




回答2:


You could use try method.

<%= car.try(label.related_to) %>

try would try to call the method on car. However, if the method (ie. make) does not exist it would throw an error.

You could make use of respond_to? to ensure that the method exist:

<%= car.try(label.related_to) if car.respond_to?(label.related_to) %>


来源:https://stackoverflow.com/questions/4800836/call-a-method-on-a-variable-where-the-method-name-is-in-another-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!