Ruby 搜索多维数组
学习 Ruby 代码的美妙之处,我想知道是否有一种简单/直接的方法可以在多维数组中进行搜索。我有一个包含 4 个索引的多数组,其中包含各种数字。我想搜索与另一个数组匹配的内容的每个索引...seudo codez
multi_array = [ [1,3,7], [3,1,4], [1,3,4], [0,9,2]]
numbers_looking_to_match = [1,5,9]
multi_array.each do | elmt |
elmt.each_with_index do |elmt, idx|
if elmt == numbers_looking_to_match.each { |e| puts "match" }
end
end
我希望它返回一个新的多数组,并删除原始多数组的所有不匹配字符。
Learning the beauty of Ruby code and I was wondering if there is a simple/straightforward to search within a multidimensional array. I have an multi array with 4 indices that contain assorted number. I want to search though each index matching the contents agains another array...seudo codez
multi_array = [ [1,3,7], [3,1,4], [1,3,4], [0,9,2]]
numbers_looking_to_match = [1,5,9]
multi_array.each do | elmt |
elmt.each_with_index do |elmt, idx|
if elmt == numbers_looking_to_match.each { |e| puts "match" }
end
end
I want this to return a new multi array with all non matching characters removed for original multi array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
Array#&
对于交叉点,Using
Array#&
for intersection,multi_array.each { |elem| number_looking_to_match.each { |x| elem.delete(x) if elem.include?(x)}
}multi_array.each { |elem| numbers_looking_to_match.each { |x| elem.delete(x) if elem.include?(x)}
}要擦除不需要的字符的每个元素:
To scrub each element of unwanted characters: