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?
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 .
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.
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.
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.
>> '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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With