0
0

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 3 years have passed since last update.

🐣【Ruby入門】Arrayを使っておみくじを実装してみる

0
Posted at

class Array(Ruby 3.0)を用いておみくじを作ってみよう。:pencil2:

sample.rb
omikuzi_array = ['大吉', '吉', '中吉', '小吉', '末吉', '凶', '大凶']

p omikuzi_array.sample
# => "大吉"
p omikuzi_array.sample
# => "小吉"

解説


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)色々調整できそう。
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?