Timmy Von Heiss
Timmy Von Heiss

Reputation: 2218

How can I create a method to replace words in an array?

the following code:

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

results in

country gender_type photos_count

I want to create a method like:

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

that can used in the above code that will substitute the strings.

Upvotes: 0

Views: 58

Answers (1)

dinjas
dinjas

Reputation: 2125

Lots of ways to do this.

One way would be to declare a Hash in your controller that looks like this:

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

And then in your view do:

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

You could also use a method as you suggested. In your controller or helper do:

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

In your view:

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

Upvotes: 2

Related Questions