Ruby 为什么退出循环需要return关键字?

Ruby 为什么退出循环需要return关键字?,ruby,Ruby,在下面的test2方法中,为什么需要return关键字才能使方法返回不等于nil 在测试中,不需要返回。程序计算的最后一行(true或false)成为返回值 def test x = gets.chomp if x == 'yes' true else false end end result = test puts result # PRINTS 'TRUE' OR 'FALSE' 但是在test2中,如果所示行上没有给出return,则该方法的返回值将为

在下面的
test2
方法中,为什么需要
return
关键字才能使方法返回不等于
nil

测试
中,不需要
返回
。程序计算的最后一行(
true
false
)成为返回值

def test
  x = gets.chomp

  if x == 'yes'
    true
  else
    false
  end
end

result = test
puts result # PRINTS 'TRUE' OR 'FALSE'
但是在
test2
中,如果所示行上没有给出
return
,则该方法的返回值将为
nil

def test2
  while true
    reply = gets.chomp.downcase

    if (reply == 'yes' || reply == 'no')
      if reply == 'yes'
        true      # RETURN NEEDED HERE
       else
        false     # RETURN NEEDED HERE
       end
      break

     else
      puts 'Please answer "yes" or "no".'
    end
  end
end

result2 = test2
puts result2        # PRINTS NIL

这些示例改编自Chris Pine的How to Program,其中指出退出循环需要返回键。但是,如果要计算的最后一行仍然是
true
false
,为什么要返回值呢?

如果不使用
return
,则方法中的最后一条语句是
while
循环本身,其计算结果为
nil
。当您跳出循环时,循环中if的结果不会被“携带”

如果您不使用
return
,则方法中的最后一条语句是
while
循环本身,其计算结果为
nil
。当您跳出循环时,循环内if的结果未“结转”

您可以使用
break
提供返回值,而

if reply == 'yes'
  break true
 else
  break false
end

您可以使用
break
提供返回值,同时

if reply == 'yes'
  break true
 else
  break false
end