0

Given this string

"In 2015, I want to know how much does iPhone 6+ cost?"

how can I return [2015, 6]?

My first attempt at this was

numbers = str.tr("^0-9", '')

but that produces 20156.

2
  • 1
    I see what you're saying @Ilya. But I think mine may be different because I'm explicitly asking for a return of an Array. Where as the other question is not. Commented Mar 28, 2017 at 20:37
  • "How much research effort is expected of Stack Overflow users?" If all you tried was a single attempt using tr, then you need to do more. Commented Mar 28, 2017 at 21:51

2 Answers 2

8

You can use scan:

numbers = str.scan(/\d+/)
# => ["2015", "6"]
Sign up to request clarification or add additional context in comments.

1 Comment

Add .map(&:to_i) for integers, plus add /\-?\d+/ for possible negative values.
1

scan is better, but this also works.

"In 2015, I want to know how much does iPhone 6+ cost?".gsub(/\D/,' ').split
  #=> ["2015", "6"] 

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.