[英]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: 这些值是由用户在不同的HashMaps中输入的,因此为了简便起见,我只是将输入输入到单个哈希中,但是调用的方法是这样的:
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"
}
}
You can use Hash#slice
and Hash#merge
to get what you want: 您可以使用Hash#slice
和Hash#merge
获得所需的内容:
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"
# }
# }
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}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.