散列数组每个何时做一定的值?

时间:2018-07-05 17:58:23

标签: ruby-on-rails ruby activerecord

我有一个名为rooms的哈希数组,看起来像这样:

[{:room=>1, :clients=>["Jim K", "Barbara K"], :rooming_request=>"Double"},
 {:room_number=>2, :clients=>["Marcy B"], :rooming_request=>"WTS"},
 {:room_number=>3, :clients=>["Stephanie C", "Stan C"], :rooming_request=>"Twin"},
 {:room_number=>4, :clients=>["Steven W"], :rooming_request=>"SS"},
 {:room_number=>5, :clients=>["Linda W"], :rooming_request=>"SS"},
 {:room_number=>6, :clients=>["Rick M", "Linda M"], :rooming_request=>"Double"},
 {:room_number=>7, :clients=>["Deb M", "William F"], :rooming_request=>"Double"}]

现在,我像这样遍历它:

rooms.each do |room|
   room[:room_number]
   room[:clients].join("<br>")

外观如下:

1 Jim K
  Barbara K

2 Marcy B

3 Stephanie C
  Stan C

etc..

如果只有某个rooming_request,我将如何输出?

例如-

rooms.where(rooming_request: "Double").each do |room|

谢谢!

1 个答案:

答案 0 :(得分:4)

使用Array#select

rooms.select { |room_hash| room_hash[:rooming_request] == 'Double' }
     .each do |room_hash|
  # Do your magic
end

rooms.each do |room|
  next unless room[:rooming_request] == 'Double'
  # Do your stuff
end