I have a hash with keys, "parameter_name" and "parameter_value", and want to produce a hash with one key-value pair, the value of "parameter_name" being the key and the value of "parameter_value" being the value. The hash looks something like this:
p = {"parameter_name"=>"NumberOfRetries", "parameter_value"=>"3"}
The way I want the output to be is like,
{"NumberOfRetries"=>"3"}
I have tried:
a = p.values.map {|v| v1,v2=v[0],v[1]; {v1=>v2} }
but doing that doesn't return the right output and it produces the following,
[{"N"=>"u"}, {"3"=>nil}]
Can somebody help me with this? Thanks.
I have a hash with keys, "parameter_name" and "parameter_value", and want to produce a hash with one key-value pair, the value of "parameter_name" being the key and the value of "parameter_value" being the value.
To get the value of "parameter_name"
you'd use: (given your example hash p
)
p["parameter_name"] #=> "NumberOfRetries"
for the value of "parameter_value"
:
p["parameter_value"] #=> "3"
A hash with a single key / value pair is created via: (assigned to a
)
a = { key => value }
Using the value of "paramter_name"
as key and the value of "parameter_value"
as value gives:
a = { p["parameter_name"] => p["parameter_value"] }
#=> { "NumberOfRetries" => "3" }
Referring to the hash values by their keys ensures that this works regardless of the hash order, or if unrelated key / value pairs are present, e.g.:
p = { "parameter_value"=>"3", "foo"=>"bar", "parameter_name"=>"NumberOfRetries" }
a = { p["parameter_name"] => p["parameter_value"] }
#=> { "NumberOfRetries" => "3" }