【问题标题】:Ruby variable each loop substitutionRuby 变量每个循环替换
【发布时间】:2012-09-08 09:44:17
【问题描述】:

我需要在 2 个地方替换 X_VARIABLE。 对于第一个 X_VARIABLE,我想保留文本“删除” 对于第二个 X_VARIABLE,我想保留 'd_cars_path'

<% @cars.each do |x| %>
    <% @a = @b.send(x) %>
    <% if @a == true %>
      <%= button_to "removeX_VARIABLE", X_VARIABLEd_cars_path(:id => @user.id), class: "btn btn-large btn-primary" %>
    <% end %>
<% end %>

我正在寻找有关变量替换语法的帮助。谢谢。

【问题讨论】:

  • 你想要 @user.id), class: "btn btn-large btn-primary" %> 这样的结果吗

标签: ruby variables substitution


【解决方案1】:

我会写:

<% @cars.each do |x| %>
  <% if @b.send(x) %>
    <%= button_to "remove#{x}", 
          send(:"#{x}d_cars_path", id: @user.id), 
          class: "btn btn-large btn-primary" %>
  <% end %>
<% end %>

【讨论】:

  • +1 我更喜欢这种方法(我也给出了它的 haml 版本)。
  • 谢谢。我不知道 send(:) 函数。
  • @Tony 您在代码中使用了send :-) 也许您不知道可以将它与隐式对象一起使用 (self)。
猜你喜欢
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多