Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Classes and objects
2.1.
Class in Ruby
2.2.
Objects in Ruby
3.
Object conversion
3.1.
Short Conversion Methods
3.1.1.
to_i
3.1.2.
to_s
3.1.3.
to_a
3.2.
Long Conversion Methods (to_str, to_int)
3.2.1.
to_str
3.2.2.
to_int
3.2.3.
Other object conversion methods
3.2.4.
to_hash()
3.2.5.
to_ary()
3.2.6.
to_r()
3.3.
Difference Between to_s & to_str In Ruby
3.4.
Difference Between to_i and to_int in Ruby
4.
Type Coercion
4.1.
Explicit casting helpers
4.2.
Implicit Coercion Methods
5.
Frequently Asked Questions
5.1.
How do you typecast in Ruby?
5.2.
How can we convert an integer to float?
5.3.
Is Ruby popular?
5.4.
How do I convert a string to an array in Ruby?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Object Conversion in Ruby

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

As we know, Ruby is an object-oriented programming language. The characteristics of object-oriented programming languages ​​include data encapsulation, polymorphism, inheritance, data abstraction, operator overloading, etc. In every object-oriented language, classes and objects play an essential role.

This article will teach us about classes and objects, how to create an object in the Ruby programming language, and object conversions.

Classes and objects

Classes in any programming language are nothing but a blueprint from which objects are created. Objects are therefore also called instances of a class. A class defines the object's properties, including a valid set of values ​​and a default value. The class also describes the nature of the object. An object is a member or "instance" of a class. Let's now learn more about objects and classes in Ruby.

Class in Ruby

In Ruby, we use the class keyword to create a class. First, we must write the keyword "class," followed by the class name. The first letter of the class name must be uppercase. The class can be terminated with the end keyword, and all data members are between the class definition and the last keyword.

Syntax:

class Class_name

end

Objects in Ruby

We can create objects in Ruby by using the new keyword. 

Syntax:

object_name = Class_name.new 
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Object conversion

Object conversion can be defined as the process of converting an object from one type to another type. There are two types of such conversions in Ruby: short conversion methods and long conversion methods. For example, if we want to convert a string method to an integer method, we can use the to_i built-in method. Let's now learn about these conversions in detail.

Short Conversion Methods

There are three types of short conversion methods: to_s, to_i, and to_a.

to_i

Ruby has a built-in method called to_i that converts any object to an integer. If the object is already an integer, it will return that object. Otherwise, it will convert the object to an integer using the default radix. This method can be applied to floats, strings, and integers.

Syntax: 

Number.to_i

Example:

num1 = 55
num2 = 12.48
puts num1.to_i
puts num2.to_i

Output:

55
12

to_s

Ruby's to_s method converts an integer to its string representation using the specified radix. If no radix is specified, it defaults to 10.

Syntax:

number.to_s(base)

Example:

num = 10
num1=48
puts num.to_s
puts num1.to_s(2)

Output:

10
110000

to_a

Ruby's built-in Arrayto_a() method returns an array containing all elements in the specified range.

Syntax:

range1.to_a()

Example:

range1 = (0..8)
puts range1.to_a()

Output:

0
1
2
3
4
5
6
7
8

Long Conversion Methods (to_str, to_int)

Ruby has two types of long conversion methods: to_str and to_int. 

to_str

Implementing the to_str method in your class tells the world that your class might not be a string but treat it like a string for all practical purposes.

Example:

class Fixnum
  def to_str
    to_s
  end
end
a = 11
puts '9' + a 

Output:

911

to_int

Ruby's to_int function converts the value of the number to an integer. If the number itself is an integer, it returns the integer only. It is an aliased version of the to_i function, which converts the number to an integer if possible.

Syntax:

Number.to_int

Example:

num1 = 21
num2 = 10.78
puts num1.to_int
puts num2.to_int

Output:

21
10

Other object conversion methods

to_hash()

The to_hash() method returns the hash representation of the hash itself. It is a hash class method.

Syntax: 

Hash.to_hash()

Example:

h1 = {one: "apple", two: "orange", three: "banana"}
puts h1.to_hash()

Output:

{:one=>"apple", :two=>"orange", :three=>"banana"}

to_ary()

The to_ary() method returns its self-array representation. It is an array class method.

Syntax

Array.to_ary()

Example:

a = [18, 22, 33, nil, 5, 6]
puts "#{a.to_ary()}\n\n"

Output:

[18, 22, 33, nil, 5, 6]

to_r()

The float to_r() is a float class method. This method returns the rational form of the float value.

Syntax: 

float.to_r()

Examples:

m = 7
n = 8.8888
puts "Rational form of m : #{m.to_r}\n\n"
puts "Rational Form of n : #{n.to_r}\n\n"

Output:

Rational form of m : 7/1
Rational Form of n : 2501974772985679/281474976710656

Difference Between to_s & to_str In Ruby

Ruby provides two ways to convert an object to a string. To_s converts an object to a string using its internal representation, while to_str returns a string that represents the object’s class name. Both methods produce the same result when called on simple types like Fixnum, Float, String, etc. If we call to_s, it will return some form of the object's string representation. An easier display of the object. We can keep the default behaviour when defining a new class or build our own. 

If we call to_str, it should return a string-like object that behaves like a string. When an object implements to_str, it will produce something that acts like a string. That means if the class is not necessarily a string, it can still be used similarly.

The main differences between the two are:

  1. to_s can return a string representation of an object.
  2. to_str is stating that the object behaves like a string.
  3. to_s is an explicit conversion, and to_str is an implicit conversion.
  4. to_s is defined on most objects and returns a string representation of this object.
  5. Defining to_str on an object is like saying, "This object behaves like a string." 
  6. If we call to_str, it should return a string-like object, not just a string representation of the object.

For example,

1. Here’s how to_s behaves on an integer:

Code:

num = 100
num1 = 1000
puts num.to_s
puts num1.to_s(2)

Output:

100
1111101000

Difference Between to_i and to_int in Ruby

The to_int method is used for conditional expressions. The to_int method checks whether the object can be considered an integer. We're not saying that whatever was in the object at that point could be converted to an integer. We say this object can always be considered an integer, regardless of its actual value. The to_i method is typically used to do the actual conversion.

Float is a class that implements both to_int and to_i. Both methods return the same result, but the presence of to_int states that a float can always be treated as an integer. This makes sense because a float always contains an integer part. If we cast a float with to_i or to_int, the float will be truncated, and only the integer part will remain.

Type Coercion

Object conversion is also called type coercion. These methods can also be classified as explicit and implicit casting helpers.

Explicit casting helpers

The casting helpers such as to_s, to_i, to_a, and to_h are explicit casting methods. They help us transform a value from one type to another.

Implicit Coercion Methods

Ruby provides methods that return a value only when objects act as a type. Such methods are called implicit coercion methods. We can ensure that the value is of the desired type through implicit coercion methods. These methods are to_str, to_int, to_ary, and to_hash.

Frequently Asked Questions

How do you typecast in Ruby?

Ruby has a robust typecasting infrastructure. Casting a value to a string with to_s, a float with to_f, an integer with to_i, etc. Even though these are helpful tools in our toolbox, they have limitations. To start, the #to_* method does not cast values as true or false.

How can we convert an integer to float?

The number value is transformed into a float using Ruby's to_f function. It returns infinity if it is too large for a float. The parameter for the function is the integer that needs to be converted to a float. The function's float value is what it returns as its return value.

Is Ruby popular?

Although much of Ruby's popularity comes from this connection, Ruby has many uses, including web scraping, static site generation, command-line tools, automation, DevOps, and data processing.

How do I convert a string to an array in Ruby?

Split () is the general syntax for using the split method. The method's argument specifies the point at which the string should be split. The split substrings will all be returned as an array.

Conclusion

In this article, we have discussed different types of object conversion in the Ruby programming language. We can implement these operations on the Rubinius platform.

We hope that this blog has helped you enhance your knowledge regarding object conversion types and if you would like to learn more, check out our articles on 8 reasons why Ruby should be your first language, Everything you should know about ruby. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations and much more!

Happy Reading!

Previous article
Object Order In Ruby
Next article
Copying Objects In Ruby
Live masterclass