Home » Ruby programming

Ruby to_s method

Ruby to_s method: Here, we are going to learn about the to_s method in Ruby programming language which is used to convert to string.
Submitted by Hrithik Chandra Prasad, on September 14, 2019

Ruby to_s method

In any program code, you accommodate various data types because there are various operations which work on specific data types only. You generally store the value of a data type into the same data type variable but this case is not possible every time. Your data may come from various external sources like Keyboard and database. So, to perform specific operations on them, you need to convert them in specific type first.

When you take input from the keyboard, the input is of string type. If you want to perform some mathematical calculations on it, then you have to convert it into an integer with the help of .to_i method.

Similarly, if you want to convert any type value into a string type, you can take help from .to_s method.

In case of the objects belonging to the user-defined class, .to_s method prints the hexadecimal code associated with that instance.

.to_s method can be called in the Ruby program with the help of the following syntax:

    (Object_name).to_s

Now, let us understand the implementation of .to_s method in a Ruby code with the help of examples.

Example 1:

=begin
Ruby program to show the implementation 
of to_s method.
=end

puts "Enter any string"
str = gets.chomp

for k in 1..5
	str.concat((k*10).to_s)
end

puts "The final string is #{str}"

Output

Enter any string
Tina
The final string is Tina1020304050

Explanation:

In the above code, you can analyze that we are concatenating the loop variable with the string. The loop variable is of integer type and can't be concatenated directly, that's why firstly; we have to convert it into a string with the help of .to_s method and then concatenating it. At last, we are printing the value of the resultant string.

Example 2:

=begin
Ruby program to show the implementation of 
to_s method.
=end

class Example
	def initialize
	end
end

class Example1
	def initialize
	end
end

obj1 = Example.new
obj2 = Example1.new

puts "The hexadecimal code of obj1 : #{obj1.to_s}"
puts "The hexadecimal code of obj2 : #{obj2.to_s}"

Output

The hexadecimal code of obj1 : #<Example:0x00000000031b12e8>
The hexadecimal code of obj2 : #<Example1:0x00000000031b1270>

Explanation:

In the above code, we are creating two classes and instantiating them. You can observe that .to_s method is overridden and printing some different types of string. This string is nothing but a hexadecimal code associated with the object with which it is called .to_s method is overridden for the objects of user-defined classes. The hexadecimal code starts with the Class name followed by the address of the object.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.