Last active
June 6, 2019 21:30
Star
You must be signed in to star a gist
Playground: test `segment` as a more broad `partition`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby's Enumerable has `partition` to split it into true and false groups. | |
evens, odds = 1.upto(5).partition(&:even?) | |
evens # => [ 2, 4 ] | |
odds # => [ 1, 3, 5 ] | |
# But what if you have more than 2 segments? Well, here I'm playing with one way to do it. | |
# Respectively outputs: | |
# [[:first, :first], [:second, :second], [:third, :third]] | |
# [[:first, :first], [:second, :third, :second, :third]] | |
# [[:first, :first], [:second, :third, :second, :third]] | |
# [[:first, :first], [:second, :second], [:third, :third]] | |
p %i( first second third first second third ).segment(&:itself) | |
p %i( first second third first second third ).segment { |i| i == :first } # Equal to `partition`. | |
p %i( first second third first second third ).segment { |i| i == :first ? 1 : 2 } | |
p %i( first second third first second third ).segment { |i| i == :first ? 1 : (i == :second ? 2 : 3) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
# Basically `partition` with more than true/false as grouping. | |
def segment(&block) | |
Hash.new.tap do |segmented| | |
each do |item| | |
(segmented[yield(item)] ||= []) << item | |
end | |
end.values | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support' | |
require 'active_support/core_ext/enumerable' # For `group_by`. | |
class Array | |
# Basically `partition` with more than true/false as grouping. | |
def segment(&block) | |
group_by(&block).values | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment