0

I have the following array.

@arr = ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"]

Now I want to extract the first two letters of each item.

@firsttwo = ["Ac", "Ba", "Ca", "Dd", "aA", "bD", "cB", "dD"]

How can I achieve this in Ruby.

I tried this but it didn't work.

    @firsttwo = @combi.select{ |item| item[0, 1]}

2 Answers 2

3

You need to use Array#map :

@arr = ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"]
@arr.map { |item| item[0..1] }
# => ["Ac", "Ba", "Ca", "Dd", "aA", "bD", "cB", "dD"]

#select selects the element from receiver, if block returns true. Now in your case item[0..1] giving a string object in each iteration, which has truthy value, thus #select selects all element from the receiver.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

@firsttwo = @arr.map { |item| item.split(",")[0] }

You are currently using select. This returns a collection where each iteration returns true. You seem to want to preform the same operation on each member of the collection without doing any testing. .map is suited for this.

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.