1

I have these two arrays

Hotel = 'hilton', 'marriot'
Price = '$350', '$375'

How would I go about merging the two arrays together and making the price a key to the hotel.

So when I access

Price[0]

It outputs

'$350' => 'hilton' (or however the correct output should be)

1 Answer 1

3

Do as below using Array#zip and Hash::[] :

Hotel = 'hilton', 'marriot'
Price = '$350', '$375'
Hash[Price.zip(Hotel)]
# => {"$350"=>"hilton", "$375"=>"marriot"}

But to meet your posted description :

Hotel = 'hilton', 'marriot'
Price = '$350', '$375'
array_of_hash = Price.each_index.map { |i| { Price[i] => Hotel[i]} }
# => [{"$350"=>"hilton"}, {"$375"=>"marriot"}]
array_of_hash[0] # => {"$350"=>"hilton"}

Now choose, whatever way suits to your need.

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

3 Comments

array_of_hash = Price.zip(Hotel).map {|a| Hash[*a] } gets rid of the unsightly index.
@CarySwoveland That's nice too,
Since I only code for fun, I can afford to always choose aesthetics. In my never-ending quest to rid the world of indices, here's another (that creates two arrays and adds two statements): hotel = Hotel.dup; price = Price.dup; Price.size.times.map { { price.shift => hotel.shift } } .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.