39
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rangeの範囲内からランダムに数値を選ぶ

Posted at

誤りの例

以下で一見良さそうなんですが、そもそもやりたいことができません。Rangeオブジェクトいっこの配列ができるので、この返り値はRangeになります。

[1 .. 10000].sample

好ましくない例

これもダメです。to_aしたらメモリに展開され、数が少なければそんなに影響ないですが、多いと悲劇になります。

(1 .. 10000).to_a.sample

よい例

Random#randは引数にRangeを渡せます。

Random.rand(1 .. 1000)
39
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?