danynl danynl - 1 year ago 67
Ruby Question

How to get values from a hash within an array

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
values in the hash matches with any of the strings in
and set the variable
to the

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

If this ran correctly
should be returned:

=> "11"
=> "22"
=> "33"
=> "44"

Answer Source

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"]


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download