Reputation: 25538
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
Reputation: 453
text = "ds.35bdg56"
x = /\d+/.match(text)
puts x #will return 35 (i hope this helps)
Upvotes: 6
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