Skip to content

Instantly share code, notes, and snippets.

View mikodagatan's full-sized avatar

Miko Dagatan mikodagatan

  • Reinteractive
  • Philippines
View GitHub Profile
@mikodagatan
mikodagatan / when_to_use_select_instead_of_pluck.md
Last active June 16, 2023 07:37
When to use .select instead of .pluck

There are articles and stackoverflow answers that sample the general opinion that pluck is the superior method to use over map and select. I agree on that with map, but I beg to differ for select on some "select" cases, and for good reason.

What are the cases?

Usually, pluck is being used when there is some special chain of queries that are needed to be called on a complicated application. A sample of this call that I usually see is:

discounted_product_ids = Product.with_discounts.where(country: 'AU').pluck(:id)
promo_product_ids = Product.with_promos.where(country: 'AU').pluck(:id)

products = Product.where(id: discounted_product_ids + promo_product_ids)