【问题标题】:How can I create a method to replace words in an array?如何创建一个方法来替换数组中的单词?
【发布时间】:2016-09-18 13:05:37
【问题描述】:

以下代码:

<% (params.keys & User::FILTERS).each do |f| %>
  <%= f %>
<% end %>

结果

国家性别_类型照片_计数

我想创建一个类似的方法:

def rename 
 country = Country of Origin 
 gender_type = Gender 
 photos_count = Number of Photos
end

可以在上面的代码中使用,将替换字符串。

【问题讨论】:

标签: ruby-on-rails


【解决方案1】:

有很多方法可以做到这一点。

一种方法是在控制器中声明一个Hash,如下所示:

@sub_words = {
  "country" => "Country of Origin",
  "gender_type" => "Gender",
  "photos_count" => "Number of Photos"
}

然后在你看来:

<% (params.keys & User::FILTERS).each do |f| %>
  <%= @sub_words.fetch(f, f) %>
<% end %>

您也可以使用您建议的方法。在你的控制器或助手中做:

def rename(filter)
  case filter
  when "country"
    "Country of Origin"
  when "gender_type"
    "Gender"
  when "photos_count"
    "Number of Photos"
  else
    filter
  end
end
helper_method :rename

在你看来:

<% (params.keys & User::FILTERS).each do |f| %>
  <%= rename(f) %>
<% end %>

【讨论】:

  • 我收到以下错误 ActionView::Template::Error (undefined local variable or method 'sub_words' for #&lt;#&lt;Class:0x007fb5e8366c30&gt;:0x007fb61b338f28&gt;):ActionView::Template::Error (undefined method 'rename' for #&lt;&lt;Class:0x007ff104324888&gt;:0x007ff13c76b7d8&gt;):
  • 抱歉,更新了我的答案。您可能需要在变量名前面加上 @ 和/或将您的 rename 方法声明为 helper_method
  • 它被传递为"country":String
猜你喜欢
  • 1970-01-01
  • 2015-05-01
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 2015-03-02
  • 1970-01-01
相关资源
最近更新 更多