[Ruby]: Update hash values with Array

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” }

I’ve tried to minimize the number of loops here. Appreciate your feedback and suggestions.

Happy Coding! 🙂

Advertisements

One thought on “[Ruby]: Update hash values with Array

  1. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s