Skip to content

购物车总额的代码为什么sum需要先define为0? #93

@dyz2102

Description

@dyz2102

<% sum = 0 %>
<% current_cart.cart_items.each do |cart_item| %>
<% sum = sum + cart_item.quantity * cart_item.product.price %>
<% end %>
Total <%= sum %> RMB

为什么需要先declare sum = 0?拿掉这一行sum为什么就变成undefined?

同样,在model里面的代码,最后倒数第二个sum为什么不会直接算出总数,还需要再写一次“sum”?

def total_price
sum = 0
cart_items.each do |cart_item|
sum += cart_item.quantity * cart_item.product.price
end
sum
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions