Ruby join array method

learn about join() array method in ruby programming language. Such as how its uses and how it will work?. This method converts the array element into string and combine the string by specific separator and return resulting string. Syntax of this method as follows.

Syntax
array.join(separator=$) -> returns a string value

Separator parameter of this method take a string pattern which is combined resultant array elements. This parameter is optional. When not provide this parameter value this method combine array element without any space.

Ruby join method example

# Our array
arr  = [1,2,3,4]

# join method
r1 = arr.join
r2 = arr.join("—")
r3 = arr.join(" ")
r4 = arr.join(" ☀ ")
r5 = arr.join(", ")

# Display array
print(" Array : ",arr)

# Display result
print("\n r1 : ",r1)
print("\n r2 : ",r2)
print("\n r3 : ",r3)
print("\n r4 : ",r4)
print("\n r5 : ",r5)
Ruby join method example 1
 Array : [1, 2, 3, 4]
 r1 : 1234
 r2 : 1—2—3—4
 r3 : 1 2 3 4
 r4 : 1 ☀ 2 ☀ 3 ☀ 4
 r5 : 1, 2, 3, 4

This method are capable to work inner array elements.

# Our array
arr  = [1,2,[true,false],3,['a','b']]

# join method
result = arr.join("-")

# Display array
print(" Array : ",arr)

# Display result
print("\n Result : ",result)
Ruby join method example 2
 Array : [1, 2, [true, false], 3, ["a", "b"]]
 Result : 1-2-true-false-3-a-b

When array elements contain custom class objects. When this method are convert object to string. See this example.

class Test 
    # Define the accessor and reader of class Test
   
    def initialize(id, name) 
        @id = id
        @name = name
    end
end


# Object of class
student = Test.new(34, "Jay")

# array
arr = [1,2,student]

# Join method
result = arr.join("-");

print(result)
Ruby join method example 3
1-2-#<Test:0x0000000278fee0>


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved