Ruby | Array sample() function
Last Updated :
06 Dec, 2019
Array#sample() : sample() is a Array class method which returns a random element or n random elements from the array.
Syntax: Array.sample()
Parameter: Array
Return: a random element or n random elements from the array.
Example #1 :
a = [ 18 , 22 , 33 , nil , 5 , 6 ]
b = [ 1 , 4 , 1 , 1 , 88 , 9 ]
c = [ 18 , 22 , 50 , 6 ]
puts "sample() method form : #{a.sample(2)}\n\n"
puts "sample() method form : #{b.sample(1)}\n\n"
puts "sample() method form : #{c.sample(3)}\n\n"
|
Output :
sample() method form : [6, nil]
sample() method form : [4]
sample() method form : [18, 22, 6]
Example #2 :
a = [ "abc" , "nil" , "dog" ]
c = [ "cat" , nil ]
b = [ "cow" , nil , "dog" ]
puts "sample() method form : #{a.sample(2)}\n\n"
puts "sample() method form : #{b.sample(1)}\n\n"
puts "sample() method form : #{c.sample(3)}\n\n"
|
Output :
sample() method form : ["dog", "abc"]
sample() method form : ["dog"]
sample() method form : ["cat", nil]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...