Enumerable Patterns
Group By Intro
group_by builds a hash where each key points to matching values.
Group By Intro
group_by_intro.rb
split_at =
numbers = [2, 4, 5, 8]
groups = numbers.group_by do |number|
number >= split_at ? "large" : "small"
end
small = groups.fetch("small", [])
large = groups.fetch("large", [])
puts "split_at=#{split_at}"
puts "small=#{small.join(",")}"
puts "large=#{large.join(",")}"
split_at =
numbers = [2, 4, 5, 8]
groups = numbers.group_by do |number|
number >= split_at ? "large" : "small"
end
small = groups.fetch("small", [])
large = groups.fetch("large", [])
puts "split_at=#{split_at}"
puts "small=#{small.join(",")}"
puts "large=#{large.join(",")}"
split_at =
numbers = [2, 4, 5, 8]
groups = numbers.group_by do |number|
number >= split_at ? "large" : "small"
end
small = groups.fetch("small", [])
large = groups.fetch("large", [])
puts "split_at=#{split_at}"
puts "small=#{small.join(",")}"
puts "large=#{large.join(",")}"
group by
`group_by` chooses a key for each item and collects items with the same key.