0

Basically I'm trying to condense this one array of hashes with the same value into another array. I'm new to Ruby and I'm trying to change this

fruit = [
 {type: 'grape', color: 'purple' },
 {type: 'grape', shape: 'round'},
 {type: 'grape', size: 'small'},
 {type: 'apple', color: 'red'},
 {type: 'apple', size: 'med'},

]

to this:

fruit = [
  {type: 'grape', color: 'purple', shape: 'round', size: 'small'}
  {type: 'apple', color: 'red', size: 'med'}
]

Any help?

6
  • What are the values of grape, purple, etc? Don't introduce methods or variables without explanation. Commented Sep 11, 2013 at 16:47
  • Whoops, sorry, mistyped. All of those are strings -- I'll have to retype. Commented Sep 11, 2013 at 16:49
  • Question is not clear. What is the rule that excludes {size: "small"} from the hash with {type: "grape"}? Commented Sep 11, 2013 at 16:51
  • Sorry, again, mistyped. No rule, should be in the output. Basically I need to condense the key/value pairs that are in many hashes with the same type. So for all the hashes with type 'grape' need to be condensed into one hash with type 'grape' holding all of the other key/value pairs stored in associating with type 'grape'. Sorry if my post was unclear. Commented Sep 11, 2013 at 16:55
  • 1
    Great. You should post that along with the question next time so we know enough about your skill level to be able to help you. =) Commented Sep 11, 2013 at 18:29

1 Answer 1

2
fruit.group_by{|h| h[:type]}.values.map{|a| a.inject(:merge)}

Result:

[
  {
    :type  => "grape",
    :color => "purple",
    :shape => "round",
    :size  => "small"
  },
  {
    :type  => "apple",
    :color => "red",
    :size  => "med"
  }
]
Sign up to request clarification or add additional context in comments.

7 Comments

It'd be awesome if we asked new users to show what they've already tried / put a little more effort into explaining our answers.
This works! Thank you! I obviously need to do more work on method chaining and manipulating arrays/hashes!
@mohawkjohn You mean "effort into explaining their questions"? If so, I agree. I sometimes keep my answer deleted for a while until the OP shows effort.
@mohawkjohn Yeah I've tried using both inject and merge but I just wasn't able to wrap my head around the ordering. Thanks again.
@sawa sorry to have annoyed you.
|

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.