Hackerrank Ruby Hash - Each Solution
- Published
- Updated
- Reading time
- 1 min read
- Length
- 150 words
You've seen the control structure each used on an array. Similarly, it is available for the Hash collection, as well.
On Hash, it works in two ways.
Consider the example
user = {"viv" : 10, "simmy" : 20, "sp2hari" : 30}Using each, each element can be iterated as
user.each do |key, value|
# some code on individual key, value
endor
user.each do |arr|
# here arr[0] is the key and arr[1] is the value
endYour task is to use each and iterate through the collection and print the key-value pair in separate lines.
Hint
puts key
puts valueSolution in ruby#
Approach 1.
def iter_hash(hash)
hash.each do |k, v|
puts k
puts v
end
endApproach 2.
def iter_hash(hash)
hash.each do |key,value|
puts key
puts value
end
endApproach 3.
def iter_hash(hash)
hash.each do |key, value|
puts key
puts value
end
end