Using slice_after to split arrays by a value
Given you have an array of objects that you may want to split apart based on a value on one of the objects, you can use slice_after
(there's also slice_before
, which behaves the same way).
array = [
{activity: "traveling", ticket: "123"},
{activity: "working", ticket: "123"},
{activity: "awaiting_assignment", ticket: ""},
{activity: "traveling", ticket: "234"},
{activity: "refueling", ticket: "234"},
{activity: "traveling", ticket: "234"},
{activity: "working", ticket: "234"},
{activity: "awaiting_assignment", ticket: ""}
]
array.slice_after { |i| i.activity == "awaiting_assignment" }
# Returns:
[
[
{activity: "traveling", ticket: "123"},
{activity: "working", ticket: "123"},
{activity: "awaiting_assignment", ticket: ""}
],
[
{activity: "traveling", ticket: "234"},
{activity: "refueling", ticket: "234"},
{activity: "traveling", ticket: "234"},
{activity: "working", ticket: "234"},
{activity: "awaiting_assignment", ticket: ""}
]
]
Tweet