Skip to content

Instantly share code, notes, and snippets.

@marinados
Created February 3, 2016 13:37
Show Gist options
  • Save marinados/c5bc2838cf46334e0ec1 to your computer and use it in GitHub Desktop.
Save marinados/c5bc2838cf46334e0ec1 to your computer and use it in GitHub Desktop.
slice method
a = ["a", "b", "c"]
a.slice(1, 2)
# => ["b", "c"]
a = ["a", "b", "c"]
a.slice_before("b").to_a
# => [["a"], ["b", "c"]]
a = ["000", "b", "999"]
a.slice_before(/[a-z]/).to_a
# => [["000"], ["b", "999"]]
a = [100, 200, 300]
a.slice_before(150..250).to_a
# => [[100], [200, 300]]
a = [1, "200", 1.3]
a.slice_before(String).to_a
# => [[1], ["200", 1.3]]
a = [1, 2, 3, 4, 5]
a.slice_before do |item|
item % 2 == 0
end
# => [[1], [2, 3], [4, 5]]
a = ["a", "b", "c"]
a.slice_after("b").to_a
# => [["a", "b"], ["c"]]
a = [1, 2, 3, 100, 101, 102]
# Create a new group when the difference
# between two adjacent items is > 10.
a.slice_when do |x, y|
(y - x) > 10
end
# => [[1, 2, 3], [100, 101, 102]]
# the slice methods don't return arrays. They return enumerables.
# That means that you can use map, each and all your other favorite enumerable methods on.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment