LoginSignup
1
0

More than 3 years have passed since last update.

【Ruby】おみくじプログラムの仕組みを解説自分用

Last updated at Posted at 2020-05-04
array = ["大吉","中吉","吉","凶"]

a = array.split(",")  #配列arrayの値をカンマで区切る。

b = a.length          # 変数Aの要素の数を数える。

c = rand(b)           #要素の数であるBからランダムに配列の番号(0から始まるやつ)を取得する。

puts a[c]
  #または
puts a[rand(b)]    #配列arrayの値をカンマで区切ったものから、先ほどランダムに取り出した配列番号の値を出力する。

もしくは、sampleメソッドを使用して

puts ["大吉","中吉","吉","凶"].sample

とすると複数の行が1行で済んでしまう。

ポイント

randメソッドは配列の範囲のランダムな数を持ってくるので、事前にlengthメソッドなどでデータを取ってくる配列の要素の数を知らせておく必要がある。

1
0
6

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
1
0