如果我想比较两个数组,并创建一个插值输出字符串,如果从数组的数组变量y中存在x我怎么能获得每个匹配元素的输出?
这就是我的尝试但却没有得到结果.
x = [1, 2, 4]
y = [5, 2, 4]
x.each do |num|
puts " The number #{num} is in the array" if x.include?(y.each)
end #=> [1, 2, 4]
Run Code Online (Sandbox Code Playgroud)
Abe*_*ker 118
您可以使用set intersection方法&:
x = [1, 2, 4]
y = [5, 2, 4]
x & y # => [2, 4]
Run Code Online (Sandbox Code Playgroud)
Sim*_*eev 16
x = [1, 2, 4]
y = [5, 2, 4]
intersection = (x & y)
num = intersection.length
puts "There are #{num} numbers common in both arrays. Numbers are #{intersection}"
Run Code Online (Sandbox Code Playgroud)
将输出:
There are 2 numbers common in both arrays. Numbers are [2, 4]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31982 次 |
| 最近记录: |