Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

output

ruby

hash

People also ask

How do I iterate a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

How do you iterate through a hash?

When we iterate over a hash, the #each method (as well as any other iteration method you use) yields the key/value pair together into the block. Inside that block, you have access to the key and the value, and can manipulate either one or both. Inside the iteration we have access to both the key and the value.

How do you check if something is a hash Ruby?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .


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.


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

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

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

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

My one line solution:

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

I think it is pretty easy to read.