how to group array in ruby
How to Group an Array in Ruby
To group an array in Ruby, you can use the group_by
method. Here are the steps to do it:
- Define an array with elements that you want to group.
- Use the
group_by
method on the array and provide a block of code that determines the grouping criteria. - The
group_by
method will return a hash where the keys represent the grouping criteria and the values represent the elements that belong to each group.
Here's an example that demonstrates how to group an array of numbers based on their evenness:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
grouped_numbers = numbers.group_by { |num| num.even? }
puts grouped_numbers
Output:
{false=>[1, 3, 5, 7, 9], true=>[2, 4, 6, 8, 10]}
In this example, the array numbers
is grouped based on whether each number is even or odd. The group_by
method takes a block of code that evaluates the evenness of each number (num.even?
). The resulting hash grouped_numbers
has two keys: false
for odd numbers and true
for even numbers. The corresponding values are arrays containing the numbers that belong to each group.
I hope this helps! Let me know if you have any further questions.