0

I have a nested array that looks like this:

@nested = [
  ['1','2','3'],
  ['1','5','9'],
  ['1','4','7'],
  ['3','5','7'],
  ['3','6','9'],
  ['7','8','9'],
  ['4','5','6'],
  ['2','5','8']
]

I'd like to take a user input of any integer (that 1..9) and find every array that has that input integer.

Not sure how to do it.

1 Answer 1

8

Use select:

num_to_search = "9"
@nested.select do |array|
  array.include? num_to_search
end
#=> [["1", "5", "9"], ["3", "6", "9"], ["7", "8", "9"]]
Sign up to request clarification or add additional context in comments.

2 Comments

I had to put if array.include?(num_to_search) puts array.inspect end to get your output. The original just gave me a sequence of true/false. I am stuck with Ruby 1.8.7 at the moment. Is that the cause?
@ScottJShea It shouldn't print anything, it should return that array of arrays. I've just verified that the return value is what I show in my answer in both Ruby 1.8.7 & 1.9.3.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.