检查一个数组是否有另一个数组中的任何元素
Check if an array has any element in another array
我有两个数组:
one = ["2cndb", "7bndb", "14accdb", "5ggdb"]
two = [["2cndb", "alive"], ["14accdb", "alive"], ["5ggdb", "not alive"]]
我想检查 two
中的每个子数组是否包含 one
的任何元素。当它出现时,我想向子数组添加一个元素 "yes"
,否则 "no"
。
我的代码是:
two.each do |item|
if (one.include?('item[0]'))
item.push("yes")
else
item.push("no")
end
end
然后我得到
two = [["2cndb", "alive", "no"], ["14accdb", "alive", "no"], ["5ggdb", "not alive", "no"]]
但是 "2cndb"
、"14accdb"
、"5ggdb"
出现在 one
中。您能指出问题出在哪里吗?
您应该只使用不带引号的 item[0]
。但是你说你想检查子数组中的所有值:在这种情况下你的解决方案仍然是错误的,所以可能的解决方案是:
one = ["2cndb", "7bndb", "14accdb", "5ggdb"]
two = [["2cndb", "alive"], ["14accdb", "alive"],
["5ggdb", "not alive"], ["foo", "bar"]]
two.map { |e| e + [(one & e).empty? ? 'no' : 'yes']}
#=> [["2cndb", "alive", "yes"], ["14accdb", "alive", "yes"],
# ["5ggdb", "not alive", "yes"], ["foo", "bar", "no"]]
我有两个数组:
one = ["2cndb", "7bndb", "14accdb", "5ggdb"]
two = [["2cndb", "alive"], ["14accdb", "alive"], ["5ggdb", "not alive"]]
我想检查 two
中的每个子数组是否包含 one
的任何元素。当它出现时,我想向子数组添加一个元素 "yes"
,否则 "no"
。
我的代码是:
two.each do |item|
if (one.include?('item[0]'))
item.push("yes")
else
item.push("no")
end
end
然后我得到
two = [["2cndb", "alive", "no"], ["14accdb", "alive", "no"], ["5ggdb", "not alive", "no"]]
但是 "2cndb"
、"14accdb"
、"5ggdb"
出现在 one
中。您能指出问题出在哪里吗?
您应该只使用不带引号的 item[0]
。但是你说你想检查子数组中的所有值:在这种情况下你的解决方案仍然是错误的,所以可能的解决方案是:
one = ["2cndb", "7bndb", "14accdb", "5ggdb"]
two = [["2cndb", "alive"], ["14accdb", "alive"],
["5ggdb", "not alive"], ["foo", "bar"]]
two.map { |e| e + [(one & e).empty? ? 'no' : 'yes']}
#=> [["2cndb", "alive", "yes"], ["14accdb", "alive", "yes"],
# ["5ggdb", "not alive", "yes"], ["foo", "bar", "no"]]