How to get a specific output iterating a hash in Ruby?

304,452

Solution 1

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

Solution 2

The most basic way to iterate over a hash is as follows:

hash.each do |key, value|
  puts key
  puts value
end

Solution 3

hash.keys.sort.each do |key|
  puts "#{key}-----"
  hash[key].each { |val| puts val }
end

Solution 4

Calling sort on a hash converts it into nested arrays and then sorts them by key, so all you need is this:

puts h.sort.map {|k,v| ["#{k}----"] + v}

And if you don't actually need the "----" part, it can be just:

puts h.sort

Solution 5

My one line solution:

hash.each { |key, array| puts "#{key}-----", array }

I think it is pretty easy to read.

Share:
304,452

Related videos on Youtube

sts
Author by

sts

Updated on July 08, 2022

Comments

  • sts
    sts almost 2 years

    I want to get a specific output iterating a Ruby Hash.

    This is the Hash I want to iterate over:

    hash = {
      1 => ['a', 'b'], 
      2 => ['c'], 
      3 => ['d', 'e', 'f', 'g'], 
      4 => ['h']
    }
    

    This is the output I would like to get:

    1-----
    
    a
    
    b
    
    2-----
    
    c
    
    3-----
    
    d 
    
    e
    
    f
    
    g
    
    4-----
    
    h
    

    In Ruby, how can I get such an output with my Hash ?

    • Allen Rice
      Allen Rice almost 15 years
      If you're iterating a hash and expecting it to be ordered, you probably need to use some other collection type
  • glenn jackman
    glenn jackman almost 15 years
    The hash keys are numbers, so '[k + "----"]' raises a TypeError (String can't be coerced into Fixnum). You need '[k.to_s + "----"]'
  • mashe
    mashe almost 15 years
    True enough. I had letters in my test version. Fixed, using the even better "#{k}----".
  • huzefa biyawarwala
    huzefa biyawarwala over 8 years
    here what if key isn't used anywhere ? . do we need to put a ? in place of key ? ex : |?, array| is this valid syntax ?
  • sepp2k
    sepp2k over 8 years
    @huzefabiyawarwala No, ? is not a valid variable name in Ruby. You can use _, but you don't need to.
  • huzefa biyawarwala
    huzefa biyawarwala over 8 years
    what i meant was if we use |k,v| for iterating over a hash, but we don't use k in our logic implementation inside our loop, so is there any way we can write like this |_, v| ?
  • sepp2k
    sepp2k over 8 years
    @huzefabiyawarwala Yes, you can write |_, v|
  • jrhicks
    jrhicks over 7 years
    what use variable name array instead of v or value?
  • Radon Rosborough
    Radon Rosborough about 7 years
    @jrhicks Because the OP has a hash whose values are arrays.