TABISH KHAN
TABISH KHAN

Reputation: 1623

print hash within array in ruby?

if I have an array with hashes inside, how do I print only the hash keyvalue pairs ?

  complex_array= [ 1,2, 3, "string", 
               {"app1"=>"123 happy street",
                "app2"=>"daf 3 street", 
                "app3"=>"random street"}, "random", {"another"=>"hash"}
               ]

I'm trying to do:

complex_array.select{|x|
 puts x["app1"];
 }

that doesn't work, because with arrays you need an index parameter (no conversion of string to integer error)

So how do I only print the values of the hash(s) without specifying the index of the hash within the array first, or is that the only way ?

Upvotes: 0

Views: 3702

Answers (2)

Snags88
Snags88

Reputation: 86

You can loop through each element of the array and determine if that class of the element is a hash. If so, then puts the key value pairs of that hash element. The second looping is necessary in case there are multiple key value pairs.

 complex_array.each do |element|
   if element.class == Hash
     element.each do |key, value|
       puts "key: #{key}, value: #{value}"
     end
   end
 end

Upvotes: 3

Cary Swoveland
Cary Swoveland

Reputation: 110675

Just select the elements that are hashes, then for each hash, print the key-value pairs:

complex_array.select { |e| e.is_a? Hash }
             .each { |h| h.each { |k,v| puts "#{k}=>#{v}" } }
  # app1=>123 happy street
  # app2=>daf 3 street
  # app3=>random street
  # another=>hash

Upvotes: 1

Related Questions