This was a simple assigned blog. We were asked just to talk about one enumerable method out of three. So I'm going to go over #group_by.
#group_by takes in an array, creates hash where key is the criteria for how you want it grouped, and the value for the key will be an array of the elements that fit that criteria from the original array.
- Use: To group up elements in an array
- Input:
array.group_by {|element| criteria}
- Output:
{"criteria"=>[elements that meet this criteria], repeat, etc.}
- Example:
- Note how it separated into true or false based on our groups. This tests the element if it is a Fixnum, or number. Here's another example:
- See, now we're more specific. You can use this for any criteria.
- This returns a hash, but doesn't store it. To store it, be sure to assign the code to a new or existing variable.
array = ["Alan", "Bob", "Susie", 1, 3, 5, "Robert"]
array.group_by {|element| element.is_a? (Fixnum)}
=> {false=>["Alan", "Bob", "Susie", "Robert"], true=>[1, 3, 5]}
array.group_by {|element| element.class}
=> {String=>["Alan", "Bob", "Susie", "Robert"], Fixnum=>[1, 3, 5]}