I have an array consisting of multiple hashes with the same structures. I also have another array filled with strings:
我有一个由多个散列组成的数组,它们具有相同的结构。我还有另一个数组,里面有字符串:
prop_array = [
{:name=>"item1", :owner=>"block1",:ID=>"11"},
{:name=>"item2", :owner=>"block2",:ID=>"22"},
{:name=>"item3", :owner=>"block3",:ID=>"33"},
{:name=>"item4", :owner=>"block4",:ID=>"44"}
]
owner_array = ["block1","block2","block3","block4"]
I want to check if any of the :owner
values in the hash matches with any of the strings in owner_array
and set the variable :partID
to the :ID
value:
我想要检查是否有:哈希表中的所有值与owner_array中的任何字符串相匹配,并设置变量:partID到:ID值:
I tried the following but it doesn't work:
我试了一下,但没用:
owner_array.each do |owner|
prop_array.each do |prop|
prop.each do |key, value|
if key[:owner] == owner.to_s
puts "YES"
partID = key[:ID]
puts partID
end
end
end
end
If this ran correctly partID
should be returned:
如果正确运行,则返回:
=> "11"
=> "22"
=> "33"
=> "44"
1 个解决方案
#1
0
I want to check if the any of the ':owner' value in the hash matches with any of the strings in owner_array
我想要检查在哈希表中是否有任何“:owner”值与owner_array中的任何字符串相匹配。
prop_array.select {|hash| owner_array.include?(hash[:owner]) }
#=> [{:name=>"item1", :owner=>"block1", :ID=>"11"}, {:name=>"item2", :owner=>"block2", :ID=>"22"}, {:name=>"item3", :owner=>"block3", :ID=>"33"}, {:name=>"item4", :owner=>"block4", :ID=>"44"}]
set the variable ":partID" to that ':ID' value
设置变量“:partID”到“:ID”值。
partID = prop_array.select { |hash| owner_array.include?(hash[:owner]) }
.map { |hash| hash[:ID] }
#=> ["11", "22", "33", "44"]
EDIT
Since you want these values to assign in a loop, go with:
因为您希望这些值在循环中赋值,请使用:
partID = prop_array.select { |hash| owner_array.include?(hash[:owner]) }.each do |hash|
# assignment happens here one by one
cell_id = hash[:ID] # or whatever logic you have to assign this ID to cell
end
#1
0
I want to check if the any of the ':owner' value in the hash matches with any of the strings in owner_array
我想要检查在哈希表中是否有任何“:owner”值与owner_array中的任何字符串相匹配。
prop_array.select {|hash| owner_array.include?(hash[:owner]) }
#=> [{:name=>"item1", :owner=>"block1", :ID=>"11"}, {:name=>"item2", :owner=>"block2", :ID=>"22"}, {:name=>"item3", :owner=>"block3", :ID=>"33"}, {:name=>"item4", :owner=>"block4", :ID=>"44"}]
set the variable ":partID" to that ':ID' value
设置变量“:partID”到“:ID”值。
partID = prop_array.select { |hash| owner_array.include?(hash[:owner]) }
.map { |hash| hash[:ID] }
#=> ["11", "22", "33", "44"]
EDIT
Since you want these values to assign in a loop, go with:
因为您希望这些值在循环中赋值,请使用:
partID = prop_array.select { |hash| owner_array.include?(hash[:owner]) }.each do |hash|
# assignment happens here one by one
cell_id = hash[:ID] # or whatever logic you have to assign this ID to cell
end