这是我试图理解的代码,目前令人困惑的部分是代码中的 :product_id,特别是“:product_id”的“:”部分 我的问题是我们怎么知道我们应该使用那个“:”?
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
最佳答案
符号:
- 基本上是字符串常量
- 被创建一次。即
:product_id
无论何时您使用它都是同一个对象。因此它们节省了内存。另一方面,如果您多次编写"product_id"
,您基本上是在创建尽可能多的字符串对象 - 不能利用 Reg-ex 和插值(大部分),除非你在符号上使用 to_s 方法
简而言之,对不需要处理或修改的短字符串常量使用符号。
例如:符号非常适合哈希等中的键。明白了吗?
关于ruby-on-rails - 我们什么时候知道应该使用符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444356/