class A
def numbers
[1,2,3,4]
end
def get_numbers(condition)
numbers = [3,5] if condition
numbers
end
end
a = A.new
a.get_numbers(true) # [3,5]
a.get_numbers(false) # nil
我希望它在第二种情况下返回 [1,2,3,4]
!
P.S. 我不是在寻找解决方案(我可以用两个不同的变量名来解决我的问题),而是在寻找对此行为的解释,ruby 是否创建了变量 numbers
在运行时本身 & 由于 if
条件而初始化为 nil
?
最佳答案
当 token 可以解释为局部变量或方法调用时,局部变量具有优先权。方法定义中的最后一个 numbers
被解释为局部变量。要使其解释为方法调用,您需要使其明确。
这可能是您想要的:
def get_numbers(condition)
return numbers = [3,5] if condition
numbers()
end
但是这段代码很臭,应该是这样的:
def get_numbers(condition)
condition ? [3,5] : numbers
end
- ruby 是否在运行时本身创建 [create] 变量
numbers
& [and] 初始化 [initialize it] 为nil
因为if
条件?
是的。无论条件是否满足,Ruby 都会解析所有内容,如果局部变量因条件不满足而未赋值,则会将其初始化为nil
。
关于Ruby 实例方法和同名条件局部变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17760732/