这是一个ruby monk练习,我很难将我的头围绕在一个特定的概念上。
例如,"soup bowl" = "soup bowl" + 1将无效,那么为什么@dishes_needed[a] = (@dishes_needed[a] || 0) + 1在下面的代码中工作是因为它们是变量而不是对象吗如果是,为什么当我最初设置a = (a||0)+1时,代码a = "Soup"不起作用:

class Dish
end

class Soup < Dish
end
class IceCream < Dish
end
class ChineseGreenBeans < Dish
end

class DeliveryTray
  DISH_BOWL_MAPPING = {
    Soup => "soup bowl",
    IceCream => "ice cream bowl",
    ChineseGreenBeans => "serving plate"
  }

  def initialize
    @dishes_needed = {}
  end

  def add(dish)
    a = DISH_BOWL_MAPPING[dish.class]
     @dishes_needed[a] = (@dishes_needed[a] || 0) + 1
  end

  def dishes_needed
      return "None." if @dishes_needed.empty?

      @dishes_needed.map { |dish, count| "#{count} #{dish}"}.join(", ")
  end
end

d = DeliveryTray.new
d.add Soup.new; d.add Soup.new
d.add IceCream.new

puts d.dishes_needed # should be "2 soup bowl, 1 ice cream bowl"

最佳答案

让我们简化@dishes_needed部分,这样您就可以理解核心概念@dishes_needed是散列,@dishes_needed[a] = (@dishes_needed[a] || 0) + 1向散列添加一个键、值对。
这是查看代码的更简单的方法。这是DISH_BOWL_映射散列:

  DISH_BOWL_MAPPING = {
    Soup => "soup bowl",
    IceCream => "ice cream bowl",
    ChineseGreenBeans => "serving plate"
  }

DISH_BOWL_MAPPING哈希中获取特定元素:
>> DISH_BOWL_MAPPING[Soup]
=> "soup bowl"

@dishes_needed是空哈希:
>> @dishes_needed = {}
=> {}

如果a = Soup,那么下面是有关代码行的操作方式:
>> a = Soup
=> Soup
>> @dishes_needed[a] = (@dishes_needed[a] || 0) + 1
=> 1
>> @dishes_needed
=> {Soup=>1}

让我们分解方程的右侧,这是令人困惑的:
>> (@dishes_needed[a] || 0) + 1
>> (@dishes_needed[Soup] || 0) + 1
# @dishes_needed[Soup] is nil because Soup hasn't been added to the hash yet
>> (nil || 0) + 1
# nil || 0 evaluates to 0 because nil and false are falsey in Ruby
>> (0) + 1
>> 1

在更新散列之后,调用to@dishes_needed[Soup]evaluate to 1:
>> @dishes_needed[Soup]
=> 1

这表示键(Soup)等于值加1(在本例中,该值尚未确定,因此结果为1)。
如果a = "Soup"a = (a||0)+1的计算结果为a = "Soup" + 1,并且不能在Ruby中添加整数和字符串如果将1转换为字符串,则表达式的计算结果正确。
a = (a||0)+1.to_s

关于ruby - 为什么变量=变量+ 1有效?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17847007/

10-13 09:03