Reputation: 26919
Here is a code I am trying to understand and the confusing part for now is the :product_id in the code, specially the ":" part of ":product_id" My question is how should we know we should use that ":" ?
def up
# replace multiple items for a single product in a cart with a single item
Cart.all.each do |cart|
# count the number of each product in the cart
sums = cart.line_items.group(:product_id).sum(:quantity)
sums.each do |product_id, quantity|
if quantity > 1
# remove individual items
cart.line_items.where(product_id: product_id).delete_all
# replace with a single item
item = cart.line_items.build(product_id: product_id)
item.quantity = quantity
item.save!
end
end
end
end
Upvotes: 1
Views: 97
Reputation: 7674
Symbols are just pointers to an object containing its name while strings are always different objects.
If you are going to repeat a name many times in your code then use one symbol which is the equivalent of using just one object.
For example if you use the string "France"
a 100 times in your code, you would prefer to use :France
. The advantage is that in the first case you would instantiate a 100 objects and in the second case just one.
In your example, maybe you are getting confused because product_id: product_id
is a Hash represented in JSON style. This would be the equivalent of :product_id => product_id
Upvotes: 2
Reputation: 5221
Symbols:
:product_id
will be the same object whenever you use it. Hence they save memory. On the other hand if you write "product_id"
multiple times, you are basically creating as many string objectsIn a nutshell, use symbols for short string constants which you don't need to process or modify.
Eg: Symbols are great for keys in Hashes etc. Get it?
Upvotes: 3