Ruby:使用||=运算符应该可以改写成'if'语句,但是好像不行。

Ruby: Using the ||= operator should be able to be rewritten in 'if' statements, but it doesn't seem to work.

我相信这行说“如果 school[grade] 为真,则将 name 铲入其中。如果为假,则为其赋值 [],然后将 [=15] 铲入其中=] 进入:

(@school[grade] || @school[grade] = []) << name

如果是这样,那应该等同于以下几行:

if @school[grade] == true 
  @school[grade] << name
else 
  @school[grade] = []
  @school[grade] << name
end

不过好像不行。我不知道我在这里错过了什么。

x == true 检查 x 是否等于 true,而不是 x 是否为真(这是一个数组)。使用 if @school[grade].

irb(main):001:0> !!5
=> true
irb(main):002:0> 5 == true
=> false

在Ruby中,nil为假,非nil的(除了false)为真。所以这是一个更好的翻译:

if @school[grade]           # if @school[grade] isn't nil or false
  @school[grade] << name    # append name to it
else 
  @school[grade] = []       # otherwise give it an empty array
  @school[grade] << name    # and then append name to it
end

else 子句可以简化为一行:@school[grade] = [name].