In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead:
>> a = "0123"
=> "0123"
>> a[0]
=> 48
I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it.
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 to_i function in Ruby converts the value of the number to int. If the number itself is an int, it returns self only. Parameter: The function takes the number which is to be converted to int. Return Value: The function returns the int value.
The to_s function in Ruby returns a string containing the place-value representation of int with radix base (between 2 and 36). If no base is provided in the parameter then it assumes the base to be 10 and returns.
The to_f function in Ruby converts the value of the number as a float. If it does not fit in float, then it returns infinity. Syntax: number.to_f. Parameter: The function takes the integer which is to be converted to float.
Or you can convert the integer to its character value:
a[0].chr
You want a[0,1]
instead of a[0]
.
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