Casting

christian.dinh2481 total contributions
Published Jul 30, 2021Updated Sep 9, 2021
Contribute to Docs
In Ruby, the language comes with a variety of building typecasting methods for conerting values from one data type to another.
Syntax
For the most part methods usually begin with to_[data-type]
.
To Integer
To convert from String to Integer, use to_i
:
meaning_of_life = "42"puts meaning_of_life.class # Output: Stringmeaning_of_life = meaning_of_life.to_iputs meaning_of_life.class # Output: Integer
To Float
To convert from String to Float-type, use to_f
:
meaning_of_life = "42.0"puts meaning_of_life.class # Output: Stringmeaning_of_life = meaning_of_life.to_fputs meaning_of_life.class # Output: Float
To Array
To convert an Object to an Array, use to_a
:
myObj = {name: "Denise",occupation: "Software Engineer"}puts myObj.to_a
The output would be:
nameDeniseoccupationSoftware Engineer
All contributors
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- BrandonDusch580 total contributions
- christian.dinh
- Anonymous contributor
- BrandonDusch
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.