Home » Ruby programming

Array.join() Method with Example in Ruby

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

Array.join() Method

In this article, we will study about Array.join() method. You all must be thinking the method must be doing something which is related to joining 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 join the Array instance with some symbol passed as the argument. This method works in the way that it joins the content of self with the symbol or if you don’t provide any symbol then it simply joins the elements and converts them into a String. The return type of this method is String. This method is one of the examples of non-destructive methods where the changes made by these methods are permanent. There is no destructive version of this method.

Syntax:

    array_instance.join
    or
    array_instance.join(symbol) 

Argument(s) required:

This method takes a symbol and that symbol may be anything that may be used to join the Array instance elements and convert them into a String.

Example 1:

=begin
  Ruby program to demonstrate JOIN method
=end	

# array declaration
lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array join implementation."
puts "Enter the Symbol"
sym = gets.chomp

puts lang.join(sym)

puts "Array elements are:"
print lang

Output

Array join implementation.
Enter the Symbol
 *
C++*Java*Python*Ruby*Perl
Array elements are:
["C++", "Java", "Python", "Ruby", "Perl"]

Explanation:

In the above code, you can observe that we are trying to create a String with the help of Array instance elements. We are asking the user for the symbol which he wants to put in between the elements of the Array instance.

Example 2:

=begin
  Ruby program to demonstrate JOIN method
=end	

# array declaration
lang = ["C++","Java","Python","Ruby","Perl"]

puts "Array join implementation."

puts lang.join

puts "Array elements are:"
print lang

Output

Array join implementation.
C++JavaPythonRubyPerl
Array elements are:
["C++", "Java", "Python", "Ruby", "Perl"]

Explanation:

In the above code, you can see that we are using the method without any argument and this has resulted in the normal Array elements joining. All the Array elements are concatenated and converted into a single String.



Comments and Discussions!

Load comments ↻





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