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.
Related videos on Youtube
Author by
sts
Updated on July 08, 2022Comments
-
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 almost 15 yearsIf you're iterating a hash and expecting it to be ordered, you probably need to use some other collection type
-
-
glenn jackman almost 15 yearsThe hash keys are numbers, so '[k + "----"]' raises a TypeError (String can't be coerced into Fixnum). You need '[k.to_s + "----"]'
-
mashe almost 15 yearsTrue enough. I had letters in my test version. Fixed, using the even better "#{k}----".
-
huzefa biyawarwala over 8 yearshere what if key isn't used anywhere ? . do we need to put a
?
in place of key ? ex :|?, array|
is this valid syntax ? -
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 over 8 yearswhat i meant was if we use
|k,v|
for iterating over a hash, but we don't usek
in our logic implementation inside our loop, so is there any way we can write like this|_, v|
? -
sepp2k over 8 years@huzefabiyawarwala Yes, you can write
|_, v|
-
jrhicks over 7 yearswhat use variable name array instead of v or value?
-
Radon Rosborough about 7 years@jrhicks Because the OP has a hash whose values are arrays.