[英]Comparing individual elements of an array and hash
我有以下哈希和数组,每个都有 8 个元素:
{1=>"2.06", 2=>"2.10", 4=>"2.00", 5=>"2.10", 6=>"2.20", 8=>"2.10", 9=>"2.10", 12=>"2.04"}
["2.06","2.10","2.00","2.10","2.20","2.10","2.10","2.04"]
我需要验证每个数组槽是否与相应的哈希值匹配。 例如, array[0]
需要等于hash[:1]
的值, array[1]
需要等于hash[:2]
等。我不想要的是将array[0]
与任何其他值进行比较hash hash[:1]
以外的散列值, array[1]
到hash[:2]
以外的任何其他值等。散列值和数组值都按照图示的确切顺序读取,因此该顺序不需要改变。 如果这些对中的任何一个不匹配,它们将失败并迭代到下一对。
我尝试制作一个嵌套循环,它遍历数组和散列。 但它所做的是将每个哈希值与一个数组槽进行比较,然后迭代到下一个数组槽并重复(参见我当前的输出代码)。 到目前为止,这是我的代码,其中包含我需要的伪代码:
array.each_with_index do |item, index|
hash.each do |key, value|
puts "Key: #{key}"
puts "Index: #{index}"
#if item[index] == key[:value1]
#print pass, else print fail
#iterate to next pair
#if item[index+1] == key[:value2]
#repeat
#...
#end
end
end
这是我的代码当前输出的内容:
Key: 1
Index: 0
Key: 2
Index: 0
Key: 4
Index: 0
Key: 5
Index: 0
...
这是我需要它输出的内容:
Key: 1
Index: 0
Pass
Key: 2
Index: 1
Pass
Key: 4
Index: 2
Fail
Key: 5
Index: 3
Pass
...
对哈希值和数组进行相等检查很容易:
puts hash.values == array
为了做你想做的事情,嵌套循环是不合适的(它遍历array
每个元素的整个hash
而不是一对一比较)。 您可以使用zip
并行迭代两者:
array.zip(hash).each_with_index do |(av, (hk, hv)), ai|
puts "Key: #{hk}"
puts "Index: #{ai}"
puts av == hv ? "pass" : "fail"
end
输出:
Key: 1
Index: 0
pass
Key: 2
Index: 1
pass
Key: 4
Index: 2
pass
Key: 5
Index: 3
pass
Key: 6
Index: 4
pass
Key: 8
Index: 5
pass
Key: 9
Index: 6
pass
Key: 12
Index: 7
pass
你可以做这样的事情
h={1=>"2.06", 2=>"2.10", 4=>"2.00", 5=>"2.10", 6=>"2.20", 8=>"2.10", 9=>"2.10", 12=>"2.04"}
a = ["2.06","2.10","2.00","2.10","2.20","2.10","2.10","2.04"]
(0).upto(a.length) do |index|
if a[index]==h[index+1]
puts "key: #{index+1}"
puts "index: #{index}"
puts "Pass"
else
puts "key: #{index+1}"
puts "index: #{index}"
puts "Failed"
end
end
您目前面临的问题是因为不需要第二个循环。
array.each_with_index do |item, index|
hash.each do |key, value|
# ^ this is not needed
而是通过提供基于索引的键来访问哈希。
# setup
hash = {1=>"2.06", 2=>"2.10", 4=>"2.00", 5=>"2.10", 6=>"2.20", 8=>"2.10", 9=>"2.10", 12=>"2.04"}
array = ["2.06","2.10","2.00","2.10","2.20","2.10","2.10","2.04"]
array.each_with_index do |array_item, index|
key = index + 1
hash_item = hash[key]
puts "Key: #{key}"
puts "Index: #{index}"
puts array_item == hash_item ? 'Pass' : 'Fail'
end
以上打印出您期望的输出。 但是,如果除了访问哈希之外不需要索引,您可以通过执行以下操作将其偏移一:
array.each.with_index(1) do |array_item, key|
hash_item = hash[key]
puts "#{key}: #{array_item == hash_item}"
end
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.