jgiunta
jgiunta

Reputation: 721

How can I match using regex integer before string?

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.*)/)

Upvotes: 0

Views: 185

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

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

Upvotes: 0

sawa
sawa

Reputation: 168101

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

Upvotes: 0

coreyward
coreyward

Reputation: 80041

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]

Upvotes: 1

Related Questions