Convert Data Types in Ruby
- You produce can contain multiple data types, it’s vital to stay in mind that you simply can usually be acting operations at intervals constant data type.
- That is, you’ll be acting arithmetic on numbers or change of integrity strings along.
- Sometimes information comes from external sources, like the keyboard, API response, or a database, and you will have to be compelled to convert it so as to figure with it. Ruby provides many ways for changing values from one data type to a different.
- You’ll convert strings to numbers, objects to strings, strings to arrays, and convert between strings and symbols.
Converting Strings to Numbers
- It provides the to_i and to_f ways to convert strings to numbers. to_i converts a string as the integer, and to_f converts a string to a float.
Let’s demonstrate this by making a little program that prompts for 2 numbers and displays the sum. Generate a brand new Ruby program referred to as adder.rb with the subsequent code:
When you run the program, you will get a shocking answer:
What is the first number? 5 What is the second number? 5 55
- According to the program, the sum of 5 and 5 is 55. You recognize that is not right, however, the PC is not technically wrong. Our program prompted for 2 numbers, however, we tend to write them in on the keyboard.
- In this program, the integer 5 was not sent but the character “5” is sent. In alternative words, our program saw each of our inputs as strings, and after you add the strings “5” and “5” along, you get a brand new string, “55”.
- To avoid this, we’ve got to convert each strings to numbers. Modify your program in order that it converts each numbers to floats by victimization the to_f method:
Run the program with again ruby adder.rb. This time you’ll see this output:
What is the first number? 5 What is the second number? 5 10.0
Again you enter 5 and 5, 10.0 will be your answer this time.
The to_i and to_f ways have some fascinating behaviors once the strings are not numeric. Verify the subsequent example:
- In this instance, changing the string “123abc” to integer leads to the integer 123. The to_i technique stops once it reaches the primary non-numeric character.
- Ruby net developers exploit this by making URLs like 15-sammy-shark, wherever 15 is an internal ID to seem to a record, however, sammy-shark offers a text description within the computer address.
- If Ruby converts 15-sammy-shark to an integer with to_i, the result’s 15, and therefore the -sammy-shark half is truncated and discarded. The integer will then be accustomed to retrieving the record from a database.
Here’s another example of integer behavior that may catch you off-guard:
"abc".to_i # 0
In this instance, the to_i technique returns zero, since none of the characters within the string can be changed.
- This could end in unsought behavior; if a user enters “abc” into your program, then you change that value into an integer and divide some number by that value, your program can crash since it cannot divide by 0.
- Ruby offers another method to perform this conversion. You’ll be able to use the integer and Float ways to convert data instead:
If you pass the integer technique a value that cannot be changed, Ruby can raise the error:
ArgumentError: invalid value for Integer(): "123abc"
You will then handle the error and supply a message to the user, asking them to supply improved data. This approach is a smaller amount convenient, however, it may end up in improved data integrity, since your data will not be coerced.
Let’s verify a way to convert alternative types of data to strings next.
Convert Data to Strings
Ruby provides the to_s technique to convert the other data type to a string:
- You’ll usually convert data to Strings once making program output.
- Let’s say we wish to stay track of an individual’s daily calorie burn when a exercising. We wish to point out this accomplish the user, which implies we’ll be printing out the string and numeric values at the constant time.
- Generate the file calories.rb with the subsequent content:
- We’re hard-coding the name and calories during this program, however, in a very real program, you’d retrieve those values from another supply.
- Run the program with ruby calories.rb.
- When you run this program, you will get this error:
TypeError: no implicit conversion of Integer into String
- Ruby will not allow you to add the calories variable to the remaining of the output, as a result of it’s an integer. We cannot simply modify it to a string by swing quotes around it, because, again, the calorie information may be coming back from somewhere we do not manage. Instead, we want to convert the calorie data to a string thus we are able to combine it into the remaining of the output.
Modify the output line thus it converts the calories to a string by victimization the to_s method:
Congratulations, Sammy! You just burned 100 calories during this workout.
Ruby’s string interpolation feature mechanically converts objects to strings for you. This is often well-liked technique for making output in Ruby programs.
Rewrite the output line of your program to use string interpolation instead:
Run the program once more and you will see the constant output.
Ruby objects all give their own to_s implementation, which can or might not be adequate for output. You’ll have to be compelled to write your own code to urge the output you are looking for or investigate alternative ways to format the information.
Note: Ruby objects additionally give the inspect technique that is nice for debugging. The inspect technique works rather like to_s. It usually returns a string illustration of the item and its information. You would not use inspect in a very production app, however, you’ll use it with puts once watching a variable whereas you are writing code.
Convert Strings to Arrays
If you have got a String, you’ll be able to convert it to Array victimization the split technique.
You will specify the character you wish to use because of the delimiter by passing it as the argument to the split technique.
Try it out. Generate a program referred to as data_import.rb that contain a string of sharks, separated by commas. The program takes the data, converts it to an array, sorts it, and prints out every element to the screen:
- Run the program with ruby data_import.rb and you’ll see this output:
Bullhead Great White Hammerhead Tiger Whale
- These arrays are very influential data structures. It determines one way to use them to process data.
At last, let’s see about converting Strings and Symbols.
Convert Strings and Symbols
- You’ll often wish to convert a symbol into a String thus you’ll be able to show it, and you will generally wish to convert a String to a symbol thus you’ll be able to use it to seem one thing up in a Hash.
- Ruby’s to_s technique works on Symbols too, thus you’ll be able to convert Symbols into Strings.
This comes in handy if you would like to show a symbol and need to convert however it’s. For instance, this program takes the symbol :first_name and converts it to the string “First name”, that is a lot of human-readable:
To convert a string to a symbol use the to_sym technique, like this:
To take the string “First name” and convert it to the symbol :first_name, You should lower-case all the letters and replace empty spaces with underscores:
You’ll discover cases wherever you will need to try and do these conversions, whether or not it’s displaying a symbol on the screen in a very human-friendly format, or employing a string to seem up a key in a hash that uses symbols for its keys. Currently, you recognize how to do.
This tutorial established a way to convert many of the vital native data types to alternative data types victimization in-built ways. You’ll be currently able to convert numbers to strings, strings to arrays, and convert between symbols and strings.