Ruby/Converting data to another type

From Meshplex

Jump to: navigation, search
Image:Ruby_on_rails_tutorials.jpg
Ruby for complete beginners
Ruby Introduction
What can I use RoR for?
Reasons for choosing RoR over other popular programming languages such as php or asp.net .What makes Ruby so much more special
Where can I find RoR? In what “forms” does it come?
How to install RoR.Solutions for both the novice and professional programmers on Windows,Mac OS X and Linux.Prerequisites.
Ruby programming tutorials for beginners:
Ruby Basics
Ruby Variables, Datatypes, Operators
Ruby Symbols
Ruby Statements
Ruby Converting data to another type: type conversion or typecasting
** More Ruby Data Conversion
Ruby Arrays, Hashes, Ranges
Ruby Functions and built in functions
Ruby Control structures
Ruby Regular expressions and blocks
Ruby Loops
Ruby Recursion
Ruby Data Structures
Ruby Methods, Classes, Modules, Namespaces
Ruby Exceptions
Ruby Object Oriented Programming
Ruby Multithreading
Ruby File Handling.Input and Output
Ruby Basic GUI
Ruby and databases.Ruby on Rails and MySQL
Ruby Basic CGI.Using fastCGI
Ruby Basic Networking and web programming
Ruby Basic Graphics
Ajax and Rails.Web 2.0 and what it means
Ruby Testing, Debugging, Automation of tasks
Ruby Apache,Capistrano, Mongrel,lighttpd – reviews and tips
Finding a Ruby on Rails ready web hosting company
BONUS: mini tutorial for a simple RoR application

[edit] Converting data to another type: type conversion or typecasting

As wikipedia says,"typecasting is the conversion of a variable's data type to another data type to bypass some restrictions imposed on datatypes"

You've already recently learned how to convert symbols to strings or integers using ".to_s" and ".to_i"

A character can also be converted to an integer by using the ".to_s" method.

To convert something to a hash you would use the ".to_h" method and to convert something to an array you would use the ".to_a" method.

How to convert strings to numbers

This is a weird one,right? How can you convert strings into numbers? well, it's possible as long the string contains numbers, otherwise you will get an error.If the string contains first numbers and then letters, only the numbers will be converted to an integer and then type conversion will stop.

Let's approach this subject by using lots of examples of real code:

x="555".to_i
 
x=Integer("555")
 
x="555string"
 
x=Integer("555string")
 
x="3.14".to_f
 
x=Float("3.14")
 
x="string".to_i
 
x=Integer("string")
 
x=" 555  "

Now let's see and explain the results of the above:

Image:Typecast.gif

Previous Next