Ruby誕生日当て問題
仕様
①私の誕生日を当ててね!
数字を入力してね!(1~31まで)
2(terminal入力)
②ハズレだよ〜、ヒントをあげるね!
私の誕生日は15日以下だよ!
3(terminal入力)
③またまたハズレだよ〜ヒントをあげるね!
私の誕生日は奇数だよ!
5(terminal入力)
④惜しいけどハズレだよ〜ヒントをあげるね!
私の誕生日は6日~10日以下だよ!
※5日刻みで設定
7(terminal入力)
⑤あと一歩!ヒントをあげるね!
私の誕生日は[9, 10, 11]のどれかだよ!
※答え+-2の範囲からランダムに3日表示する
9(terminal入力)
⑥やったね!最後まで考えてくれてありがとう!
or
⑥'全部外れたねwwwどんまい!正解は9日でした〜また遊んでね!
※1~31以外の数字を入力すると、「その値は無効だよ!」と表示され終了します。
※途中で正解したら、「なんでわかったの!?天才!正解だよ☆」と褒めてくれます。
押さえておきたいポイント
1.randメソッド
乱数、つまりランダムな数値を生成してくれるメソッド。
rand(5)とすると0から4までの数値になりますが、rand(1..5)は1から5までの数値になるので注意。
2.sampleメソッド
配列の要素を1つランダムに返してくれるメソッド。配列が空の場合はnilを返します。
また、sample(3)のように引数に整数を指定すると、その数だけ要素をランダムに取り出し配列で返します。要素の順番もランダムになります。
3.to_iとto_sメソッドの使い分け
to_iメソッド → 文字から数値
to_sメソッド → 数値から文字
これが私の精一杯です。
もっとコードをスッキリさせる方法を教えてください。
puts "私の誕生日を当ててね!\n数字を入力してね!(1~31まで)"
birth = rand(1..31)
yosoku = gets.to_i
def yosoku7(birth,yosoku)
if birth == yosoku
puts "なんでわかったの!?天才!正解だよ☆"
elsif birth != yosoku
hint = [birth , birth + 1 ,birth - 1,birth + 2,birth -2]
puts "あと一歩!ヒントをあげるね!"
puts "私の誕生日は" + hint.sample(3).to_s + "日のどれかだよ!"
yosoku8 = gets.to_i
if yosoku8 == birth
puts "やったね!最後まで考えてくれてありがとう!"
else
puts "全部外れたねwwwどんまい!正解は#{birth}日でした〜また遊んでね!"
end
end
end
def yosoku5(birth,yosoku)
if birth == yosoku
puts "なんでわかったの!?天才!正解だよ☆"
elsif birth != yosoku
puts "惜しいけどハズレだよ〜ヒントをあげるね!"
if birth <= 5
puts "私の誕生日は5日以下だよ!"
yosoku6 = gets.to_i
return yosoku7(birth,yosoku6)
elsif birth > 5 && birth < 11
puts "私の誕生日は6日~10日以下だよ!"
yosoku6 = gets.to_i
return yosoku7(birth,yosoku6)
elsif birth > 10 && birth < 16
puts "私の誕生日は11日~15日以下だよ!"
yosoku6 = gets.to_i
return yosoku7(birth,yosoku6)
elsif birth > 15 && birth < 21
puts "私の誕生日は16日~20日以下だよ!"
yosoku6 = gets.to_i
return yosoku7(birth,yosoku6)
elsif birth > 22 && birth < 32
puts "私の誕生日は21日~31日以下だよ!"
yosoku6 = gets.to_i
return yosoku7(birth,yosoku6)
else
puts "値が無効だよ!"
end
end
end
def yosoku3(birth,yosoku)
if birth == yosoku
puts "なんでわかったの!?天才!正解だよ☆"
elsif birth != yosoku
puts "またまたハズレだよ〜ヒントをあげるね!"
if birth % 2 == 0 && birth < 32
puts "私の誕生日は偶数だよ!"
yosoku4 = gets.to_i
return yosoku5(birth,yosoku4)
elsif birth % 2 != 0 && birth < 32
puts "私の誕生日は奇数だよ!"
yosoku4 = gets.to_i
return yosoku5(birth,yosoku4)
else
puts "値が無効だよ!"
end
end
end
if birth == yosoku
puts "なんでわかったの!?天才!正解だよ☆"
elsif birth != yosoku && yosoku < 32
puts "ハズレだよ〜、ヒントをあげるね!"
if birth < 16
puts "私の誕生日は15日以下だよ!"
yosoku2 = gets.to_i
return yosoku3(birth,yosoku2)
elsif birth > 15 && birth < 32
puts "私の誕生日は15日より上だよ!"
yosoku2 = gets.to_i
return yosoku3(birth,yosoku2)
else
puts "値が無効だよ!"
end
else
puts "値が無効だよ!"
end