Tony Stark
Tony Stark

Reputation: 25538

(Ruby) Is there a function to easily find the first number in a string?

For example, if I typed "ds.35bdg56" the function would return 35. Is there a pre-made function for something like that or do I need to iterate through the string, find the first number and see how long it goes and then return that?

Upvotes: 18

Views: 7865

Answers (3)

testr
testr

Reputation: 453

text = "ds.35bdg56"
x = /\d+/.match(text)
puts x #will return 35 (i hope this helps)

Upvotes: 6

DigitalRoss
DigitalRoss

Reputation: 146043

>>  'ds.35bdg56'[/\d+/]
=> "35"

Or, since you did ask for a function...

$ irb
>> def f x; x[/\d+/] end
=> nil
>> f 'ds.35bdg56'
=> "35"

You could really have some fun with this:

>> class String; def firstNumber; self[/\d+/]; end; end
=> nil
>> 'ds.35bdg56'.firstNumber
=> "35"

Upvotes: 24

glenn mcdonald
glenn mcdonald

Reputation: 15488

text[/\d+/].to_i

Upvotes: 5

Related Questions