Skip to main content

Ruby Set to_a method

In Ruby programming, the to_a() set method is used to convert the set into an array. This method are create new array which contains set element, But order of objects is uncertain. The syntax of this method as follows.

set.to_a() -> new array

When set have no element then this method return an empty array.

Example of to_a() set method

# Example 1
require "set"

s = Set[1,2,[true,false],'A','B']

# Convert set into an array 
a = s.to_a

# Display array values
print("a : ",a)   
Ruby set to_a method example 1
a : [1, 2, [true, false], "A", "B"]
# Example 2
require "set"

s2 = # empty set
s1 =[1,2,true,false,s2])

# Convert set into an array 
a1 = s1.to_a
a2 = s2.to_a

# Display array values
print("a1 : ",a1)  
print("\na2 : ",a2)  
Ruby set to_a method example 2
a1 : [1, 2, true, false, #<Set: {}>]
a2 : []


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