如何从数组中的散列中获取值
How to get values from a hash within an array
我有一个由多个具有相同结构的散列组成的数组。我还有另一个充满字符串的数组:
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"]
我想检查散列中的任何 :owner
值是否与 owner_array
中的任何字符串匹配,并将变量 :partID
设置为 :ID
值:
我尝试了以下但它不起作用:
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
如果 运行 正确 partID
应该返回:
=> "11"
=> "22"
=> "33"
=> "44"
I want to check if the any of the ':owner' value in the hash matches
with any of the strings in 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 = prop_array.select { |hash| owner_array.include?(hash[:owner]) }
.map { |hash| hash[:ID] }
#=> ["11", "22", "33", "44"]
编辑
由于您希望在循环中分配这些值,请使用:
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
我有一个由多个具有相同结构的散列组成的数组。我还有另一个充满字符串的数组:
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"]
我想检查散列中的任何 :owner
值是否与 owner_array
中的任何字符串匹配,并将变量 :partID
设置为 :ID
值:
我尝试了以下但它不起作用:
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
如果 运行 正确 partID
应该返回:
=> "11"
=> "22"
=> "33"
=> "44"
I want to check if the any of the ':owner' value in the hash matches with any of the strings in 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 = prop_array.select { |hash| owner_array.include?(hash[:owner]) }
.map { |hash| hash[:ID] }
#=> ["11", "22", "33", "44"]
编辑
由于您希望在循环中分配这些值,请使用:
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