Do you think IIT Guwahati certified course can help you in your career?
No
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
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.
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.
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:
to_s can return a string representation of an object.
to_str is stating that the object behaves like a string.
to_s is an explicit conversion, and to_str is an implicit conversion.
to_s is defined on most objects and returns a string representation of this object.
Defining to_str on an object is like saying, "This object behaves like a string."
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.