Ruby 比较实例变量的相等性
我对Ruby不熟悉Ruby 比较实例变量的相等性,ruby,Ruby,我对Ruby不熟悉 class X attr_accessor :minX, :maxX, :minY, :maxY def initialize @minX = 0, @maxX = 4, @minY = 0, @maxY = 4 if @minX == @minY && @maxX == @maxY # do stuff else # not square end end end 这总是会进入e
class X
attr_accessor :minX, :maxX, :minY, :maxY
def initialize
@minX = 0, @maxX = 4, @minY = 0, @maxY = 4
if @minX == @minY && @maxX == @maxY
# do stuff
else
# not square
end
end
end
这总是会进入else子句-为什么?我认为这与定义实例变量的方式有关,最终会导致
@maxX=4
@minY=0
@maxY=4
@minX=[0, 4, 0, 4]
所以它永远是假的。如果您真的想把它们放在一行中,您可以这样做(或遵循解决方案)
否则,您可以将它们分别放在一行中
这与Rubys多重分配有关,其中:
foo, bar = [1, 2] # foo = 1; bar = 2
foo, bar = 1, 2 # foo = 1; bar = 2
foo, bar = 1 # foo = 1; bar = nil
如果要将作业放在一行上,则作业应如下所示:
@minX, @maxX, @minY, @maxY = 0, 4, 0, 4
有道理,我已经做了太多的Groovy了。当我从另一种语言转换过来时,我仍然对这种特性感到困惑:)我认为最好的解决方案是“把它们放在一行中”。“不要使用;将语句和表达式分开。作为推论,每行使用一个表达式。”是的,我同意,在回答问题之前,我在irb中尝试过这样做,我认为这是值得注意的。我认为Doug的答案也是很好的,特别是对于分配某个方法返回的数组。
@minX, @maxX, @minY, @maxY = 0, 4, 0, 4