Array#sample() : sample() es un método de clase Array que devuelve un elemento aleatorio o n elementos aleatorios de la array.
Sintaxis: Array.sample()
Parámetro: Array
Devuelve: un elemento aleatorio o n elementos aleatorios de la array.
Ejemplo 1 :
# Ruby code for sample() method # declaring array a = [18, 22, 33, nil, 5, 6] # declaring array b = [1, 4, 1, 1, 88, 9] # declaring array c = [18, 22, 50, 6] # sample method example 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"
Producción :
sample() method form : [6, nil] sample() method form : [4] sample() method form : [18, 22, 6]
Ejemplo #2:
# Ruby code for sample() method # declaring array a = ["abc", "nil", "dog"] # declaring array c = ["cat", nil] # declaring array b = ["cow", nil, "dog"] # sample method example 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"
Producción :
sample() method form : ["dog", "abc"] sample() method form : ["dog"] sample() method form : ["cat", nil]
Publicación traducida automáticamente
Artículo escrito por mayank5326 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA