本文簡要介紹ruby語言中 Random.rand 的用法。
用法
rand → float
rand(max) → number
rand(range) → number
當 max 是 Integer 時,rand 返回大於或等於零且小於 max 的隨機整數。與 Kernel.rand 不同,當 max 為負整數或零時,rand 引發 ArgumentError 。
prng = Random.new
prng.rand(100) # => 42
當 max 是 Float 時,rand 返回一個介於 0.0 和 max 之間的隨機浮點數,包括 0.0 和不包括 max 。
prng.rand(1.5) # => 1.4600282860034115
當 range 是 Range 時,rand 返回一個隨機數,其中 range.member?(number) == true 。
prng.rand(5..9) # => one of [5, 6, 7, 8, 9]
prng.rand(5...9) # => one of [5, 6, 7, 8]
prng.rand(5.0..9.0) # => between 5.0 and 9.0, including 9.0
prng.rand(5.0...9.0) # => between 5.0 and 9.0, excluding 9.0
範圍的開始值和結束值都必須響應減法(-)和加法(+)方法,否則 rand 將引發 ArgumentError 。
相關用法
- Ruby Random.random_bytes用法及代碼示例
- Ruby Random.bytes用法及代碼示例
- Ruby Random.urandom用法及代碼示例
- Ruby Random.new_seed用法及代碼示例
- Ruby Random.seed用法及代碼示例
- Ruby Random.srand用法及代碼示例
- Ruby Random.add用法及代碼示例
- Ruby Random.prng1 ==用法及代碼示例
- Ruby Random hex()用法及代碼示例
- Ruby Random random_number()用法及代碼示例
- Ruby Random new_seed()用法及代碼示例
- Ruby Random bytes()用法及代碼示例
- Ruby Random base64()用法及代碼示例
- Ruby Random urlsafe_base64()用法及代碼示例
- Ruby Random srand()用法及代碼示例
- Ruby Random random_bytes()用法及代碼示例
- Ruby Random rand()用法及代碼示例
- Ruby Random seed()用法及代碼示例
- Ruby Random new()用法及代碼示例
- Ruby Random uuid()用法及代碼示例
- Ruby Range.end用法及代碼示例
- Ruby Range new()用法及代碼示例
- Ruby Range.size用法及代碼示例
- Ruby Range last()用法及代碼示例
- Ruby Range.last用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Random.rand。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
