语法错误,带有“?”的意外 tOP_ASGN 错误在变量名中

syntax error, unexpected tOP_ASGN error with "?" in variable name

为什么 Test.foo 有效,但 Test2.foo?失败。

它似乎没有'?',但我更愿意有?跟随对话,它是一个布尔值。

syntax error, unexpected tOP_ASGN

作品:

class Test
  def foo
    @foo ||= true  # => true
  end           # => :foo

end  # => :foo

失败:

class Test2
  def foo?
    @foo? ||= true  # => true
  end           # => :foo

end  # => :foo

? 符号可以出现在方法名称的末尾,但 @foo 是实例 变量 ,而不是方法。变量名称

中不允许使用 ?