Ruby 循环中未读取变量

Ruby variable not read in loop

Ruby新手更糊涂

如果我从第 4 行删除 discountgiven == false,则条件中的代码有效。

如果我把它加回去,代码就不起作用。

我做错了什么?

discountgiven变量作用域有问题吗?

  discountgiven = false
  Input.cart.line_items.each do |item|
    product = item.variant.product
    if product.tags.include? 'device-ePod' && discountgiven == false
      discount_to_apply = item.line_price * (1.0)
      item.change_line_price(item.line_price - discount_to_apply, {message: 'Free Epod'})
      discountGiven = true
    end
  end

在条件中使用括号:

变化:

if product.tags.include? 'device-ePod' && discountgiven == false

if product.tags.include?('device-ePod') && discountgiven == false

您之前的逻辑被评估为 if product.tags.include?('device-ePod' && discountgiven == false)

此外,spickermann 的建议,您可能在 discountGiven 中输入错误。应该是 discountgiven.