Ruby 赋值与运算符详解
1. 赋值相关概念
赋值操作在 Ruby 编程中是基础且重要的部分,不同类型的赋值有着不同的规则和用途。
1.1 方法与变量的混淆示例
class Ambiguous
def x; 1; end # A method named "x". Always returns 1
def test
puts x # No variable has been seen; refers to method above: prints 1
# The line below is never evaluated, because of the "if false" clause. But
# the parser sees it and treats x as a variable for the rest of the method.
x = 0 if false
puts x # x is a variable, but has never been assigned to: prints nil
x = 2 # This assignment does get evaluated
puts x # So now this line prints 2
end
end
在这个示例中, x 最初被当作方法调用,直到解析器看到 x = 0 if false 这行代码,即使这行代码不会被执行,但解析器会将后续的
超级会员免费看
订阅专栏 解锁全文
8

被折叠的 条评论
为什么被折叠?



