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
2009-10-08 16:41:02
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
2009-10-08 17:38:53
Ok, updated for the rather cool [/\d+/] expression. I didn't know about that.
DigitalRoss
2009-10-08 17:53:14
+2
A:
text = "ds.35bdg56"
x = /\d+/.match(text)
puts x #will return 35 (i hope this helps)
testr
2009-10-08 16:43:55
Cleaner than the other solutions. If you want it as an integer, then you'll need `/\d+/.match(text)[0].to_i`.
Ben Alpert
2009-10-08 17:13:02
or if you want a string, add `.to_s`. As is, it returns a *MatchData* object.
DigitalRoss
2009-10-08 18:00:35
Why don't you try it out yourself first, if you are unsure about your knowledge. Half true knowledge does not aid anybody.
johannes
2009-10-08 20:40:06
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
2009-10-09 16:59:09