根据其他数组中的值从哈希数组中选择

时间:2016-03-21 11:29:35

标签: arrays ruby

我有这些数组。我想只选择:teacher数组中@teachers值的实例,并将它们放在@filtered_courses中。

@teachers = ["KAP", "CWD"]
@courses = [
  {:gruppnamn=>"ESM15/15MUSINS01Str", :kurskod=>"MUSINS01S", :teacher=>"MWN", :class=>"ESM15", :points=>100.0, :kvot=>nil, :tim=>nil},
  {:gruppnamn=>"ESM15/15MUSMUS01", :kurskod=>"MUSMUS01", :teacher=>"KAP", :class=>"ESM15", :points=>100.0, :kvot=>nil, :tim=>nil},
  {:gruppnamn=>"Hälsostudion/15år2", :kurskod=>"IDRIDR01", :teacher=>"CWD", :class=>"ESSA", :points=>100.0, :kvot=>nil, :tim=>nil}
]

1 个答案:

答案 0 :(得分:3)

尝试:

@filtered_courses = @courses.select { |x| @teachers.include? x[:teacher] }
# => [{:gruppnamn=>"ESM15/15MUSMUS01", :kurskod=>"MUSMUS01", :teacher=>"KAP", :class=>"ESM15", :points=>100.0, :kvot=>nil, :tim=>nil},
#     {:gruppnamn=>"Hlsostudion/15r2", :kurskod=>"IDRIDR01", :teacher=>"CWD", :class=>"ESSA", :points=>100.0, :kvot=>nil, :tim=>nil}]