简体   繁体   中英

All keys from hash with matching array values in Rails 4

I have a hash such as:

CHAR_MAP = {
  :x => %w[something]
  :y => %w[something2 something]
  :z => %w[something3 something1]
  :r => %w[something something3]
  ...
  ...
}

And I have another array

x = ['something', 'something3']

Now for the hash CHAR_MAP I want a list of keys for which all the values in it's corresponding value array are a part of the array x

So for array x we should get the keys x and r as output

@recommendation_factors.each do |rf|
  @rec_list = CHAR_MAP.detect{|h| h == rf.recommendation_factor}
end

I tried the above but it keeps on returning an empty array. :/

试试这个

CHAR_MAP.keys.select { |k| (CHAR_MAP[k] - x).empty? }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM