0
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.

2
  • I think you need to show a 'dynamic' example. Commented Apr 10, 2014 at 2:12
  • In future I suggest you hold off for awhile before selecting an answer. A quick selection discourages others from providing other, possibly better, answers, and imo is disrespectful to anyone still preparing an answer when the green checkmark is applied. (The second point does not apply to me, incidentally, as I began work on my answer after you had accepted an answer.) Commented Apr 10, 2014 at 15:29

2 Answers 2

2

You could do with:

array.group_by { |t| t.split(/\s*>\s*/).first }.values
Sign up to request clarification or add additional context in comments.

Comments

1

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"]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.