Enumerable.flat_map / group_by / tally
| Since: | Ruby 2.7(2019) |
|---|
Methods for flattening, grouping, and aggregating collections. Useful for data summarization tasks.
Syntax
collection.flat_map { |element| expression }
# Groups elements by the block's return value as a key.
collection.group_by { |element| key }
# Returns a hash with the count of each element's occurrences.
collection.tally
# Flattens a nested array.
array.flatten
array.flatten(depth)
Method List
| Method | Description |
|---|---|
| flat_map | Applies the block to each element and returns a flattened array of the results (one level deep). |
| group_by | Returns a hash where keys are the block's return values and values are arrays of matching elements. |
| tally | Counts occurrences of each element and returns a hash in the form {element => count}. |
| flatten | Recursively flattens nested arrays. An optional argument limits the depth of flattening. |
Sample Code
sample_enumerable_flat_map_group_by_tally.rb
sentences = ["member_a value_x", "member_b value_y"]
words = sentences.flat_map { |s| s.split(" ") }
puts words.inspect # ["member_a", "value_x", "member_b", "value_y"]
# Use group_by to group fighters by team.
fighters = [
{ name: "member_a", team: "team_x" },
{ name: "member_b", team: "team_y" },
{ name: "member_c", team: "team_z" },
{ name: "member_d", team: "team_z" }
]
by_team = fighters.group_by { |f| f[:team] }
puts by_team["team_x"].map { |f| f[:name] }.inspect # ["member_a"]
puts by_team["team_z"].map { |f| f[:name] }.inspect # ["member_c", "member_d"]
# Use tally to count occurrences of each element.
teams = ["team_x", "team_y", "team_x", "team_z", "team_y", "team_x"]
counts = teams.tally
puts counts.inspect # {"team_x"=>3, "team_y"=>2, "team_z"=>1}
# Get the most frequent element.
most_common = counts.max_by { |_, count| count }
puts "Most common: #{most_common[0]} (#{most_common[1]} times)" # Most common: team_x (3 times)
Running the code produces the following output:
ruby enumerable_flat_map_group_by_tally.rb
["member_a", "value_x", "member_b", "value_y"]
["member_a"]
["member_c", "member_d"]
{"team_x"=>3, "team_y"=>2, "team_z"=>1}
Most common: team_x (3 times)
Overview
flat_map combines map and flatten(1) into a single operation. It is useful when you want to generate an array from each element and collect the results into a flat list. group_by is handy for classifying data, and it returns a hash.
tally was added in Ruby 2.7, making it easy to count element occurrences. In earlier versions, you had to implement the same logic using each_with_object or inject. It is particularly useful for tasks like log analysis or vote tallying where frequency counting is required.
If you find any errors or copyright issues, please contact us.