O
O
Ord EO2019-10-16 17:25:41
ruby
Ord EO, 2019-10-16 17:25:41

How to combine 2 hashes into one in an array?

There is an array with 2 hashes like this

arr = [{:name => "Tom", :surname => "Johns", :age => "100"}, {:name => "Jack", :surname => "Hill", :age => "20"} ]

You need to get one from him
arr = [{:name => "Tom", :surname => "Johns", :age => "100", :name => "Jack", :surname => "Hill", :age => "20"} ]

or, even better, just a hash
arr = {:name => "Tom", :surname => "Johns", :age => "100", :name => "Jack", :surname => "Hill", :age => "20"}

What is the easiest way to do this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GeneAYak, 2019-10-16
@GeneAYak

no way, you can't have two identical keys in a hash

O
oh_shi, 2019-10-16
@oh_shi

No, there cannot be two or more identical keys in the hash.

S
Sergey Blokhin, 2020-02-19
@TITnet

Such a Hash cannot be obtained.
Try the line you want to get:

> arr = {:name => "Tom", :surname => "Johns", :age => "100", :name => "Jack", :surname => "Hill", :age => "20"}
(irb):1: warning: key :name is duplicated and overwritten on line 1
(irb):1: warning: key :surname is duplicated and overwritten on line 1
(irb):1: warning: key :age is duplicated and overwritten on line 1

In this case, there will be warnings for each repeated key.
And as a result, only the value of the last key will be written to the Hash.
hash = {foo: 42, foo: 43} # => { foo: 42 }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question