1

I am unsure how to select the second item from each array in a two-dimensional array given a condition on the first. Here is a similar example to what I am trying to accomplish:

If you have a 2-dimensional array in Ruby, [[1,'a'],[2,'b'],[3,'c'],[4,'d']], how could you create an array with only the letters that are in an array with an even number? (Assuming each sub-array has the same format: [number, letter])

Although this code does not work, I assumed a solution would be similar to:

array1 = [[1,'a'],[2,'b'],[3,'c'],[4,'d']]
array2 = array1.each do |num, letter|
  if num.even?
    return letter
  end
end

I want the value of array2 after running this to be ['b', 'd'].

3 Answers 3

2

You can do that with collect and compact combination:

array1.collect { |num, letter| letter if num.even? }.compact

First, you collect all the results of the if statement, then you compact to remove all the nil occurrences.

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

1 Comment

Does this alter the original array as well? --edit: I have tested it and it does not; thank you!
1
arr.each_with_object([]) { |(n,s),arr| arr << s if n.even? }
  #=> ["b", "d"] 

I would have added explanatory comments but could not find anything that required explanation.

Comments

1

For verbosity, select every array where the number is even, and then map their last element:

array1.select { |num, _| num.even? }.map(&:last)
# ["b", "d"]

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.