yuuki blog

プログラミング をアプトプットしています。

if,else問題 Ruby(2)

問題

ECサイトのポイント付与サービスで、
購入金額が999円以下の場合、3%のポイント
購入金額が1000円以上の場合、5%のポイント
このように付与されるポイントを出力するメソッド問題です。

ただし誕生日の場合はポイントが5倍になります。
誕生日の場合はtrue, 誕生日でない場合はfalseで表し、小数点以下をすべてのポイント計算が終わったあとに切り捨てる問題です。

出力例:

calculate_points(500, false) → ポイントは15点です
calculate_points(2000, false) → ポイントは100点です
calculate_points(3000, true) → ポイントは750点です

自分の答え
def calculate_points(amount, is_birthday)
  if (amount <= 999) && (is_birthday  == true )
    point = amount * 0.03 * 5
  elsif
    (amount <= 999) && (is_birthday  != true )
    point = amount * 0.03
  elsif
    (amount >= 999) && (is_birthday  == true )
    point = amount * 0.05 * 5
  else
    point = amount * 1.05
  end
  puts "ポイントは#{point.floor}点です"
end

模範解答

def calculate_points(amount, is_birthday)
  if amount <= 999
    point = amount * 0.03
  else
    point = amount * 0.05
  end
  if is_birthday
    point = point * 5
  end
  puts "ポイントは#{point.floor}点です"
end

自分は、4パターンの分岐をしましたが、模範解答では先に購入金額の分岐をし、その後誕生日の分岐をし最後に小数点を取り除いています。