Question

array = ["a > 1 2 3", "a > 4 5 6", "a > 7 8 9", "b > 1 2 3", "b > 4 5 6", "b > 7 8 9", "b > 10 11 12"]

I'm trying to group/split an array by the beginning value of the string. I know I can use group_by if the elements are static...

array.group_by{|t| t[0]}.values

array = [["a > 1 2 3", "a > 4 5 6", "a > 7 8 9"], ["b > 1 2 3", "b > 4 5 6", "b > 7 8 9", "b > 10 11 12"]]

but anything before " > " is dynamic so I don't know how to 'match' 'a', 'b' to be bale to group them.

Was it helpful?

Solution

You could do with:

array.group_by { |t| t.split(/\s*>\s*/).first }.values

OTHER TIPS

This is another way you could do it:

Code

array.sort.chunk { |str| str[/^[a-z]+\s>/] }.map(&:last)

Explanation

array = ["a > 1 2 3", "a > 4 5 6", "a > 7 8 9", "b > 1 2 3",
         "b > 4 5 6", "b > 7 8 9", "b > 10 11 12"]
a = array.sort
  #=> ["a > 1 2 3", "a > 4 5 6", "a > 7 8 9",
  #    "b > 1 2 3", "b > 10 11 12", "b > 4 5 6", "b > 7 8 9"]
enum = a.chunk { |str| str[/^[a-z]+\s>/] }
  #=> #<Enumerator: #<Enumerator::Generator:0x0000010304ee40>:each>

To view the contents of the enumerator enum:

enum.to_a
  #=> [["a >", ["a > 1 2 3", "a > 4 5 6", "a > 7 8 9"]],
  #    ["b >", ["b > 1 2 3", "b > 10 11 12", "b > 4 5 6", "b > 7 8 9"]]]

enum.map(&:last)
  #=> [["a > 1 2 3", "a > 4 5 6", "a > 7 8 9"],
  #    ["b > 1 2 3", "b > 10 11 12", "b > 4 5 6", "b > 7 8 9"]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top