1

I have an array like this:

["b3", "a3", "a5", "b2"]

and I need to get it to this:

[["b3", "b2"] ["a3", "a5"]]

I have tried various things including:

["b3", "a3", "a5", "b2"].map { |i| i.include? 'a' }
# => returns [false, true, true, false]
["b3", "a3", "a5", "b2"].detect { |i| i.include? 'a' }
# returns "a3"

Is there an simple way for this to be done?

Thanks

2 Answers 2

5
a = ["b3", "a3", "a5", "b2"]

a.group_by { |s| s[0] }.values
  #=> [["b3", "b2"], ["a3", "a5"]] 

Enumerable#group_by produces:

h = a.group_by { |s| s[0] }
  #=> {"b"=>["b3", "b2"], "a"=>["a3", "a5"]}

and then we use Hash#values to extract the values:

h.values
  #=> [["b3", "b2"], ["a3", "a5"]] 
Sign up to request clarification or add additional context in comments.

Comments

0

Before reading this answer @Cary's answer is optimised and best. But I think what you were trying to do is this

["b3", "a3", "a5", "b2"].select{|e| e.include?('a')}
=> ["a3", "a5"]

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.