-3

Newbie here. Scratching my head.

I have 2 Arrays:

arr1 = ["a", "b", "c", "d"]
arr2 = ["1", "2", "3", "4"]

I want to make a Hash using arr1 elements as the key and arr2 elements as the value. I want arr2 (or arr1, doesn't really matter) to be random.

Result example:

hash = {"a"=>"3", "b"=>"1", "c"=>"2", "d"=>"4"}
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
Collin
  • 1
  • Stackoverflow also has documentation and many examples, you can check it here: http://stackoverflow.com/documentation/ruby/288/hashes/8854/conversion-to-and-from-arrays#t=201610192303377711573 – JCorcuera Oct 19 '16 at 23:05
  • Possible duplicate of [Combine two Arrays into Hash](http://stackoverflow.com/questions/5174913/combine-two-arrays-into-hash) – JCorcuera Oct 19 '16 at 23:07

2 Answers2

3

So there are a fair number of ways to do this, but I'll do it in my favorite way

arr1.zip(arr2.shuffle).to_h

This shuffles (randomizes) arr2 so arr2 becomes ['3', '1', '2', '4'] (for example) and then zips arr1 and arr2 together into a multidimensional array [['a', '3'], ['b', '1'], ['c', '2'], ['d', '4']]. Then to_h turns this into a hash with the first element as the key and the second as the value.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
0

I'm pretty sure similar questions were answered in S.O. before, like here.

Anyway, you can just do:

> hash = Hash[arr1.zip(arr2.shuffle)]
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4"}

Tip: don't forget to take an extensive look at basic structures' documentation.

Community
  • 1
  • 1
Asche
  • 109
  • 4