Hi Folks,
In this small tutorial, I am writing a program that updates value of each element in hash with a given array values.
Given that:
h = { h1: 'value1', h2: 'value2', h3: 'value3', h4: 'value4' }
a = [ '1', '2', '3', '4' ]
Where h is a Hash and a is an Array
Output we would like to achieve here is:
h = { h1: 'value1_1', h2: 'value2_2', h3: 'value3_3', h4: 'value4_4' }
Let’s code it:
h = { h1: 'value1', h2: 'value2', h3: 'value3', h4: 'value4' }
a = [ '1', '2', '3', '4' ]
h.each_with_index do |(k, v), i|
break if a.size > h.keys.size
a.each_with_index { |val, index|
if i == index
h[k] = v.to_s + ‘_’ + val.to_s
end
}
end
p h.inspect
# Output => h = { :h1 => “value1_1”, :h2 => “value2_2”, :h3 => “value3_3”, :h4 => “value4_4” }
class MyLittleProgram | |
def execute | |
h = { h1: 'value1', h2: 'value2', h3: 'value3', h4: 'value4' } | |
a = [ '1', '2', '3', '4' ] | |
h.each_with_index do |(k, v), i| | |
break if a.size > h.keys.size | |
a.each_with_index { |val, index| | |
if i == index | |
h[k] = v.to_s + '_' + val.to_s | |
end | |
} | |
end | |
end | |
end | |
e = MyLittleProgram.new | |
p e.execute | |
# Output => h = { :h1 => "value1_1", :h2 => "value2_2", :h3 => "value3_3", :h4 => "value4_4" } |
I’ve tried to minimize the number of loops here. Appreciate your feedback and suggestions.
Happy Coding! 🙂
Small and concise:
h = { h1: ‘value1’, h2: ‘value2’, h3: ‘value3’, h4: ‘value4’ }
a = [ ‘1’, ‘2’, ‘3’, ‘4’ ]
h.each_with_index do |(k, v), i|
break if a.size > h.keys.size
a.each_with_index {|val, index| h[k] = “#{v}_#{val}” if i == index }
end
puts h