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 1 year has passed since last update.

【Ruby】mapで回す必要ある?

Last updated at Posted at 2022-07-25

リファクタのメモです。
間違っていればご指摘お願いします!

背景

今回りファクタするコードが最終的に行いたいことは、過去の各商品の2つの値とある各商品の2つの値を比較です。
そのために、preivous_itemsを定義しています。
(元のコードを編集しているので、細かいところは、気にせずでお願いします。)

def check_sample  
  previous_items = items.map do |item|
    next if item.quantity.zero?
    [item.user_id, item.quantity]
  end

  new_items = new_sample.items.group(:user_id).count
  # [[user_id,quantity],[2,4],[3,0]] == [[1,3],[2,4],[3,0]]
  preivous_items == new_items
end

元のコード

previous_items = items.map do |item|
  next if item.quantity.zero?
  [item.user_id, item.quantity]
end

リファクタ後のコード

previous_items = items.where.not(quantity: 0)
                       .pluck(:user_id, :quantity)

0
0
4

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?