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】送料無料メソッド

Last updated at Posted at 2021-01-31

【コード】

product = 2000

def shopping (p)
 if p < 3000
    q = p + 500
    puts "送料込み#{q}円"
 else
    puts "送料無料#{p}円"
 end
end

shopping(product)

【出力】

送料込み2000円

【解説】
ネットショップでよく見かける、¥〇〇円以上で送料無料という仕組みをメソッドにしてみます。
今回は¥3000以上であれば送料が無料になるという設定です。

product(商品)という変数を定義して数値(値段)を代入します。
標準入力から値を取得する場合は、

product = gets.to_i

となります。

shoppingメソッドを定義して、実引数()にproductを入れ、仮引数(p)に渡します。

¥3000以上か、¥3000以下かの条件を判定したいので今回はif文を使いました。

if p < 3000
    q = p + 500
    puts "送料込み#{q}円"

今回の設定では、¥3000以上の場合は送料無料であるため、
¥3000円以下場合は、送料である500をを足し算して、変数qへ代入
文字列の中に#{q}と記述し、文章として出力します。

else
    puts "送料無料#{p}円"

ifの条件を満たさなかった場合、つまりproduct変数の値が3000以上の場合は、実引数pをそのままの値#{p}として文章に組み込んで出力します。

設定する値を操作したい場合は

if p < 3000

の3000の部分を設定したい値に変えると、その価格として設定することができます。

¥1500以上で送料無料としたい場合

if p < 1500

という感じです。

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?