tags:

views:

158

answers:

3

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?

+5  A: 
>>  '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"
DigitalRoss
This works, but it involves way more human typing and computer processing than necessary. Much easier to pluck out the thing you want than to replace all the stuff you don't want!
glenn mcdonald
Ok, updated for the rather cool [/\d+/] expression. I didn't know about that.
DigitalRoss
+2  A: 
text = "ds.35bdg56"
x = /\d+/.match(text)
puts x #will return 35 (i hope this helps)
testr
Cleaner than the other solutions. If you want it as an integer, then you'll need `/\d+/.match(text)[0].to_i`.
Ben Alpert
or if you want a string, add `.to_s`. As is, it returns a *MatchData* object.
DigitalRoss
x will be the string `"35"` if you want the integer value, try `x.to_i`
rampion
Why don't you try it out yourself first, if you are unsure about your knowledge. Half true knowledge does not aid anybody.
johannes
Updated. I was unsure about my reply because I'm new at ruby (and at programming) but of course I tried it out before posting :)
testr
+2  A: 
text[/\d+/].to_i
glenn mcdonald