1

I have a list of objects that have key attribute and value attribute.

I would like to convert it to an object that contains attributes named as keys with the values.

Example will make it clearer...

This

[{
    :key => "key1",
    :value => "value1"
  }, {
    :key => "key2",
    :value => "value2"
}]

Should become like this:

{
  :key1 => "value1"
  :key2 => "value2"
}

I'm sure there is one line to make it happen Thanks

3 Answers 3

4

Using Hash::[], Array#map:

a = [{
    :key => "key1",
    :value => "value1"
  }, {
    :key => "key2",
    :value => "value2"
}]

Hash[a.map { |h| [h[:key], h[:value]] }]
# => {"key1"=>"value1", "key2"=>"value2"}

Hash[a.map { |h| h.values_at(:key, :value) }]
# => {"key1"=>"value1", "key2"=>"value2"}

Hash[a.map { |h| [h[:key].to_sym, h[:value]] }]
# => {:key1=>"value1", :key2=>"value2"}

a.each_with_object({}) {|h,g| g.update({h[:key].to_sym => h[:value]}) }
# => {:key1=>"value1", :key2=>"value2"}
Sign up to request clarification or add additional context in comments.

2 Comments

Here's another, ft: a.each_with_object({}) {|h,g| g.update {h[:key].to_sym => h[:value]}. +1
@CarySwoveland, Thank you for the comment. I updated the answer with your solution.
1
Hash[array.map(&:values)]
#=> {"key1"=>"value1", "key2"=>"value2"}

3 Comments

The OP wants the new keys to be symbols.
@CarySwoveland, ha, it won't be so elegant with symbolizing keys :)
That was my suspicion. From an educational viewpoint, I think bending the question a little is OK when it permits an interesting solution. Really like your specs.
1

Just to promote the to_h a bit:

[{
    :key => "key1",
    :value => "value1"
  }, {
    :key => "key2",
    :value => "value2"
}].map(&:values).map{|k,v| [k.to_sym,v]}.to_h

# => {:key1=>"value1", :key2=>"value2"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.