Ruby: Type Conversion

By Xah Lee. Date: .

Ruby does not automatically convert between strings and integers.

Each string or number object has methods to convert to other types.

String to Int, String to Float

# ruby

# string to int
p "3".to_i == 3

# string to float
p "3".to_f == 3.0

Int to String, Int to Float

# ruby

# int to string
p 3.to_s == "3"

# int to float
p 3.to_f == 3.0

Float to String, Float to Int

# ruby

# float to string
p 3.0.to_s == "3.0"

# float to int
p 3.0.to_i == 3

WARNING: decimal number such as 3. must be written with 0 at end, like this 3.0, because dot is used for method call.

# ruby

# float number must end with dot and digit

p 5/2 == 2

p 5/2.0 == 2.5

# p 5/2.
# syntax error, unexpected end-of-input, expecting '('

Ruby, List Classes and Methods