0

I have a string like "1 first - 22 second - 7 third", and I need to get the integer value for each item. For example, if I want get the third value they will return 7.

I tried with this code but it doesn't work:

item = detail.scan(/( - )\d( second.*)/)
1
  • Do you mean the third number each time? Any integer in the string? Commented Dec 31, 2011 at 18:31

3 Answers 3

1

scan is great for some data, but if you want to make sure you don't just collect garbage data you probably need something a little more structured for this. A quick split on the record separator " - " ensures each item is separated from the others before extracting the integers from the item.

your_string = "1 first - 22 second - 7 third"
items = your_string.split ' - '
numbers = items.map { |item| item[/\d+/].to_i }

#=> [1, 22, 7]
Sign up to request clarification or add additional context in comments.

Comments

0
"1 first - 22 second - 7 third".split(" - ").map(&:to_i)

Comments

0

Use the right regex:

str = "1 first - 22 second - 7 third"

str.scan(/\d+/).map{ |i| i.to_i } # => [1, 22, 7]

If you need access to a particular value use an index into the returned values:

str.scan(/\d+/).map{ |i| i.to_i }[-1] # => 7
str.scan(/\d+/).map{ |i| i.to_i }[2] # => 7
str.scan(/\d+/).map{ |i| i.to_i }.last # => 7

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.