當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Ruby Array sample()用法及代碼示例


Array#sample():sample()是一個Array類方法,它從數組中返回一個隨機元素或n個隨機元素。

用法:Array.sample()

參數:數組


返回:數組中的一個隨機元素或n個隨機元素。

示例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"

輸出:

sample() method form : [6, nil]

sample() method form : [4]

sample() method form : [18, 22, 6]

示例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"

輸出:

sample() method form : ["dog", "abc"]

sample() method form : ["dog"]

sample() method form : ["cat", nil]



相關用法


注:本文由純淨天空篩選整理自mayank5326大神的英文原創作品 Ruby | Array sample() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。