SylverEspeon
SylverEspeon

Reputation: 1

Merge two hash as sub-hashes in ruby

What I have:

{
  :url=>"http://localhost:something",
  :platformName=>"Windows",
  :foodName=>"taco",
  :Version=>"1",
  :browser=>"Edge"
}

These values were entered by the user in different HashMaps so I just made the input into a single hash for the ease, but the method called is like this:

def initialize(opts)
     @object = super Class::SuperClass.for(:remote,hash)
    end

What I want the hash to look like is some thing like this:

hash =   {
          :url=>"http://localhost:something", 
          :SubHash=> {
              :url=>"http://localhost:something",
              :platformName=>"Windows",
              :foodName=>"taco",
              :Version=>"1",
              :browser=>"Edge"
          }
        }

Upvotes: 0

Views: 79

Answers (2)

Daniel Dobrick
Daniel Dobrick

Reputation: 11

Why not simply do

hash_a = { foo: bar }
hash_b = { a: 1, b: 2, c: 3 }

hash_a[:sub_hash] = hash_b

which will result in

{
  foo: bar
  sub_hash:
    { a: 1, b: 2, c: 3}
}

Upvotes: 0

Simple Lime
Simple Lime

Reputation: 11090

You can use Hash#slice and Hash#merge to get what you want:

hash = {
  :url=>"http://localhost:something",
  :platformName=>"Windows",
  :foodName=>"taco",
  :Version=>"1",
  :browser=>"Edge"
}

output = hash.slice(:url).merge(SubHash: hash)
# => {
#   :url=>"http://localhost:something",
#   :SubHash=>{
#     :url=>"http://localhost:something",
#     :platformName=>"Windows",
#     :foodName=>"taco",
#     :Version=>"1",
#     :browser=>"Edge"
#   }
# }

Upvotes: 1

Related Questions