[英]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
任何字符串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
則應返回partID
:
=> "11"
=> "22"
=> "33"
=> "44"
我想檢查哈希中的任何 ':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"}]
將變量 ":partID" 設置為那個 ':ID' 值
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.