Home » Ruby programming

Array.replace() Method with Example in Ruby

Ruby Array.replace() Method: Here, we are going to learn about the Array.replace() method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 03, 2020

Array.replace() Method

In this article, we will study about Array.replace() method. You all must be thinking the method must be doing something related to replacing the Array instance with something. It is not as simple as it looks. Well, we will figure this out in the rest of our content. We will try to understand it with the help of syntax and demonstrating program codes.

Method description:

This method is one of the examples of the Public instance method which is specially defined in the Ruby library for Array class. This method is used to replace the Array instance with another Array instance. This method works in the way that it replaces the content of self with the elements of another Array. It may truncate it or expand it as well. This method is one of the examples of destructive methods where the changes made by these methods are permanent. There is no non-destructive version of this method.

Syntax:

    array_instance.replace(array_instance)

Argument(s) required:

This method takes an array instance as the parameter. It will give you an exception if you do not provide any array instance.

Example 1:

=begin
  Ruby program to demonstrate replace method
=end

# array declaration
Heart = ["Unconfident","Sad","No friends","Trust issues","Passing days"]

puts "Array replace implementation."
squad = ["Saksham","Nikhil","Ayush","Amisha","Satyam","Living days"]

Heart.replace(squad)

puts "Array elements are:"
print Heart

Output

Array replace implementation.
Array elements are:
["Saksham", "Nikhil", "Ayush", "Amisha", "Satyam", "Living days"]

Explanation:

In the above code, you can see that we are replacing the elements of Heart array with the elements of squad array. This method is a destructive method as changes made by it are permanent.

Example 2:

=begin
  Ruby program to demonstrate replace method
=end

# array declaration
Heart = ["Unconfident","Sad","No friends","Trust issues","Passing days"]

puts "Array replace implementation."
Heart.replace(["Saksham","Nikhil","Ayush","Amisha","Satyam","Living days"])

puts "Array elements are:"
print Heart

Output

Array replace implementation.
Array elements are:
["Saksham", "Nikhil", "Ayush", "Amisha", "Satyam", "Living days"]

Explanation:

In the above code, you can see that we are replacing the elements of Heart array with the elements of squad array. This method is destructive as changes made by it are permanent. It is not necessary that you need to declare an Array instance first then pass into the method. You can directly pass elements as shown in the above example.



Comments and Discussions!

Load comments ↻





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