Ruby each loop based on array

166 Views Asked by At

I have an array like this:

@airports = [
  ['Malaysia', 'Alor Setar', 'AOR'],
  ['Malaysia', 'Bintulu', 'BTU'],
  ['Malaysia', 'Ipoh', 'IPH'],
  ['Malaysia', 'Johor Bahru', 'JHB'],
  ['Indonesia', 'Kuching', 'KCH'],
  ['Indonesia', 'Labuan', 'LBU'],
  ['Indonesia', 'Langkawi', 'LGK'],
  ['Indonesia', 'Miri', 'MYY'],
  ['Indonesia', 'Penang', 'PEN'],
]

then in my view:

<select name="from" class="form-control select2">
    <% @airports.each do |airport| %>
      <optgroup label="<%= airport[0] %>">
        <option value="<%= airport[2] %>" <%= @params[:from] == airport[2] ? "selected" : "" %>>
          <%= "#{airport[1]} (#{airport[2]})" %>
        </option>
      </optgroup>
    <% end %>
  </select>

which gives the result like this:

Result

How can I group it for each country? I mean like this:

Malaysia
Alor Setar
Bintulu
Ipoh
Johor

Indonesia
Kuching
Labuan
Langkawi
Penang
Miri

1

There are 1 best solutions below

1
On BEST ANSWER

In your view, you can do something like:

<% countries = @airports.group_by{|a| a.first} %>
<% countries.each do |country, airport| %>
  <optgroup label="<%= country %>">
    <% airport.each do |a| %>
      <option value="<%= a[1] %>"></option>
    <% end %>
  </optgroup>
<% end %>

PS: This is just to give you a rough idea, I'm missing the logic you used for <option value> in my example. Hope you can fix it accordingly.