从哈希数组中选择仅包含在另一个数组中的元素

时间:2019-01-25 00:19:51

标签: arrays ruby hash

我有两个数组:

arr = ["test", "hello", "year"]

arr_hashes = [{"value": "yes", "key":"test"},{"value": "no", "key":"hello"},{"value": "noway", "key":"yessir"},{"value": "never", "key":"year"}]

我想返回:

new_arr = [{"value": "yes", "key":"test"},{"value": "no", "key":"hello"},{"value": "never", "key":"year"}]

我没有的东西根本不会过滤:

arr_hashes.select {|x| x['key'].include?(arr)}

1 个答案:

答案 0 :(得分:1)

arr.include?(x['key'])

相反

如此

arr_hashes.select { |x| arr.include?(x['key']) }

接收消息include?的对象是一个数组,而参数是您想知道它是否包含在数组中的元素