Join_hash that receives three hashes and returns the union of the hashes

Hello,

I’m learning Ruby and need to join hashes. I’ve tried concatenation, and
creating a new hash to and running the push method to the new array. I
can’t seem to figure out the direction to do this.

=begin
Defines a method join_hash that receives three hashes and returns the
union of the hashes. Cannot use merge.
=end

def join_hash(fruit, weight, taste)

end

#hashes
fruit = {name: ‘pineapple’}
weight = {weight: ‘1 kg’}
taste = {taste: ‘good’}

#test
p join_hash(fruit, weight, taste) == {:name=> ‘pineapple’, :weight=> ‘1
kg’, :taste=> ‘good’}

Hi Joseph,

have a look at hash#merge:
http://ruby-doc.org/core-2.2.0/Hash.html#method-i-merge

def join_hash(fruit, weight, taste)
fruit.merge(weight).merge(taste)
end

I wasn’t allowed to use merge, but i was able to figure it out. :slight_smile:

def join_hash(*args)
joined = Hash.new

args.each do |element|
element.each do |k, v|
joined[k] = v
end
end

joined
end

Sorry, well, what about this as an alternative:

def join_hash(*hashes)
hashes.reduce({}) do |memo, hash|
memo[hash.keys.first] = hash.values.first
memo
end
end

The functions aren’t the same though, because you can merge hashes with
different numbers of keys and elements…

def join_hashes(*args)
args.reduce({}) do |memo, hash|
hash.each {|k, v| memo[k] = v}
memo
end
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs