Skip to content

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

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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