Ruby中的“and return除非为nil”语句

Ruby中的“and return除非为nil”语句,ruby,Ruby,我有以下代码: 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 为什么?正如评论中所说,这不起作用,因为实际上是puts,因此您可以从show\u msg函数

我有以下代码:

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

为什么?

正如评论中所说,这不起作用,因为实际上是puts,因此您可以从show\u msg函数中明确返回某些内容,或者使用p作为示例

def test
  show_msg and return unless nil
  puts "This line can not be executed"
end

def show_msg
 p "exit here"
end

test

正如在评论中所说的,这不起作用,因为实际上是puts,所以您可以从show_msg函数显式返回某些内容,或者使用p作为示例

def test
  show_msg and return unless nil
  puts "This line can not be executed"
end

def show_msg
 p "exit here"
end

test

我不知道你们想用它做什么,除非零;这是不可操作的,因为nil永远不会是真正的值。在Ruby中,nil是除false本身之外的一个值,在布尔真值测试上下文中被认为是false。说“零”是假的是令人困惑的,因为它不等于“假”,所以红宝石学家反而说“零”是假的

无论如何,返回,除非nil与普通返回相同


缺少显式返回语句的show_msg方法将返回其中最后一条语句的值。该语句是一个puts,返回nil。所以show_msg也会返回nil,因为nil是假的,所以在返回之前会发生短路。因此,不会执行返回,Ruby继续下一行并执行它。

我不确定您想用除非nil做什么;这是不可操作的,因为nil永远不会是真正的值。在Ruby中,nil是除false本身之外的一个值,在布尔真值测试上下文中被认为是false。说“零”是假的是令人困惑的,因为它不等于“假”,所以红宝石学家反而说“零”是假的

无论如何,返回,除非nil与普通返回相同


缺少显式返回语句的show_msg方法将返回其中最后一条语句的值。该语句是一个puts,返回nil。所以show_msg也会返回nil,因为nil是假的,所以在返回之前会发生短路。因此,不会执行返回,Ruby继续下一行并执行它。

顺便说一句,您在测试的第一行上的返回不会执行,因为show_msg返回nil。顺便说一句,您在测试的第一行上的返回不会执行,因为show_msg返回nil。这只是一个语法测试。实际上是:show_msg并返回,除非@variable这只是一个语法测试。实际上是:show_msg并返回,除非@variable