4

I'm trying to combine two arrays into a hash.

@sample_array = ["one", "Two", "Three"]
@timesheet_id_array = ["96", "97", "98"]

I want to output the results into a hash called @hash_array. Is there a simple way to combine the two in a code block so that if you call puts at the end it looks like this in the console

{"one" => "96", "Two" => "97", "Three" => "98"}

I think this could be done in one or two lines of code.

5 Answers 5

41

try this

keys = [1, 2, 3]
values = ['a', 'b', 'c']
Hash[keys.zip(values)]

thanks

Sign up to request clarification or add additional context in comments.

4 Comments

+1, but it's a been a long time since you can write Hash[keys.zip(values)]
remove flatten or it won't work, Hash takes pairs. As a semantic nit-picking, I think it's important for collections to have plural names: keys and values.
@tokland - It does work with flatten, in both MRI 1.8.7 and 1.9.3. You're right that it's not needed there (it used to be, once).
Hooray! I finally get to use zip! Ruby idioms for the win.
8
@hash_array = {}
@sample_array.each_with_index do |value, index|
  @hash_array[value] = @timesheet_id_array[index]
end

1 Comment

@RubyDude1012: not that this is bad, but in a language where you have the abstractions zip and Hash in the core, definitely it's not the idiomatic way to do it.
2

Imho that looks best:

[:a,:b,:c].zip([1,2,3]).to_h

# {:a=>1, :b=>2, :c=>3}

Comments

1

Dr. Nic suggests 2 options explained well at http://drnicwilliams.com/2006/10/03/zip-vs-transpose/

1 Comment

only that the flattening is not needed anymore.
0
@hash_array = {}
0.upto(@sample_array.length - 1) do |index|
  @hash_array[@sample_array[index]] = @timesheet_id_array[index]
end
puts @hash_array.inspect

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.