我有以下代码:
def test
show_msg and return unless nil
puts "This line can not be executed"
end
def show_msg
puts "exit here"
end
test
输出:
exit here
This line can not be executed
我期望唯一的在线:
exit here
为什么?
我有以下代码:
def test
show_msg and return unless nil
puts "This line can not be executed"
end
def show_msg
puts "exit here"
end
test
输出:
exit here
This line can not be executed
我期望唯一的在线:
exit here
为什么?
as said in the comments, this doesn't work because puts actually returns nil, so you can either explictly return something from your show_msg function, or either use p for instance
def test
show_msg and return unless nil
puts "This line can not be executed"
end
def show_msg
p "exit here"
end
test
我不确定你想用unless nil;做什么 那是无操作的,因为nil永远不会是真正的价值。(在 Ruby 中,nil除了false它自身之外,它是在布尔真值测试上下文中被认为是假的一个值。nil当它不等于 时,说“是假的”是令人困惑的false,所以 Ruby 主义者反而说这nil是“假的”)。
反正return unless nil就是和plain一样return。
您的show_msg方法缺少显式return语句,将返回其中最后一条语句的值。该语句是 a puts,它返回nil。所以show_msg也返回nil,因为nil是错误的,所以and在它到达 之前短路return。因此,return没有执行,Ruby 继续到下一行并执行它。