Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

ruby

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?

like image 344
Tony Stark Avatar asked Oct 08 '09 16:10

Tony Stark


People also ask

How do you get the first element of a string in Ruby?

In Ruby, we can use the built-in chr method to access the first character of a string. Similarly, we can also use the subscript syntax [0] to get the first character of a string. The above syntax extracts the character from the index position 0 .

How do you find the part of a string in Ruby?

Accessing Characters Within a String To print or work with some of the characters in a string, use the slice method to get the part you'd like. Like arrays, where each element corresponds to an index number, each of a string's characters also correspond to an index number, starting with the index number 0.

How do you get an integer from a string in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

How do you remove the first character of a string in Ruby?

The chr method removes the first character of a string in Ruby. It removes the one-character string at the beginning of a string and returns this character.


1 Answers

>>  '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"
like image 138
DigitalRoss Avatar answered Oct 14 '22 03:10

DigitalRoss