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.

配列同士の計算

Posted at

自作のECサイトでカート内商品の合計金額を算出が必要となったため、色々試してみたところ一番しっくりくる記述法があったため忘れないように記録。

total_price.rb
 # items = CartItem.includes(:product)  //商品情報をincludesで取得
  def total_price(items)
    quantity = items.pluck(:quantity)  # :quantity(購入個数) のレコードの配列を取得

  # quantity = {1, 2, 3}

    price = items.pluck(:price)        # :price(購入金額)のレコードの配列を取得

  #  price = {1500, 1200, 1000}

    total_price = quantity.zip(price).map{|q,p| q*p}.sum   

  # .zip(price) = {[1, 1500], [2, 1200], [3, 1000]} <----quantityとpriceの配列をzipで結合
  # .map{|q,p| q*p} = {1500, 2400, 3000} <----mapで商品ごとの個数*金額を算出
  # .sum <----最後にsumで合計金額を算出

    total_price = add_tax(total_price)  # 消費税を計算
    return total_price
  end

これで合計金額の算出完了!!以上!!!!

0
0
2

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?