class Array(Ruby 3.0)を用いておみくじを作ってみよう。
sample.rb
omikuzi_array = ['大吉', '吉', '中吉', '小吉', '末吉', '凶', '大凶']
p omikuzi_array.sample
# => "大吉"
p omikuzi_array.sample
# => "小吉"
解説
- Arrayのsampleメソッド(Ruby 3.0)を使用しました。
- ランダムに要素を取得してくれる。(Kernel.#srand(Ruby 3.0)が有効)
-
Arrayの#sample(n)
のように要素を指定して取得することもできる。
sample.rb
omikuzi_array = ['大吉', '吉', '中吉', '小吉', '末吉', '凶', '大凶']
p omikuzi_array.shuffle.first
# => "大吉"
p omikuzi_array.shuffle.first
# => "小吉"
解説
- Arrayのshuffle(Ruby 3.0)を使用しました。
-
Arrayの#shuffle
で配列の要素をランダムにシャッフルします。 -
first
で配列の先頭の要素を返します。要素がなければnil
を返します。
-
所感
- if文やeachなど使用せず、シンプルに書けたのが良かった。
- Randomも指定できるので、sample(random: Random)、shuffle(random: Random)色々調整できそう。