Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Convert Integer to String

Tags:

arrays

ruby

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.

like image 869
Chris Bunch Avatar asked Aug 27 '08 04:08

Chris Bunch


People also ask

How do you convert an int to a string in Ruby?

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.

What is TO_I in Ruby?

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.

What does TO_S do in Ruby?

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.

What is TO_F in Ruby?

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.


2 Answers

Or you can convert the integer to its character value:

a[0].chr
like image 64
Joseph Pecoraro Avatar answered Oct 02 '22 13:10

Joseph Pecoraro


You want a[0,1] instead of a[0].

like image 38
SCdF Avatar answered Oct 02 '22 14:10

SCdF