给出以下方法:
def some_method
:value
end
Run Code Online (Sandbox Code Playgroud)
以下语句按预期工作:
some_method || :other
# => :value
x = some_method || :other
# => :value
Run Code Online (Sandbox Code Playgroud)
但是以下陈述的行为让我感到困惑:
some_method = some_method || :other
# => :other
Run Code Online (Sandbox Code Playgroud)
它创建一个名为some_methodexpected 的局部变量,以及后续调用以some_method返回该局部变量的值.但为什么要分配:other而不是:value?
我知道这可能不是一件明智的事情,并且可以看出它是如何模棱两可的,但我认为应该在考虑任务之前对作业的右侧进行评估......
我已经在Ruby 1.8.7和Ruby 1.9.2中测试了这个,结果相同.
干杯!
保罗
ruby有一些边缘情况很难解释,因为解析会带来一些有趣的问题.我在这里列出其中两个.如果你知道更多,那么添加到列表中.
def foo
5
end
# this one works
if (tmp = foo)
puts tmp.to_s
end
# However if you attempt to squeeze the above
# three lines into one line then code will fail
# take a look at this one. I am naming tmp2 to
# avoid any side effect
# Error: undefined local variable or method ‘tmp2’ for main:Object
puts tmp2.to_s if (tmp2 = foo)
Run Code Online (Sandbox Code Playgroud)
这是另一个.
def x
4
end
def y
x = 1 if false …Run Code Online (Sandbox Code Playgroud) ruby ×2