Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 为什么1.9.2和1.8.7中的begin/rescue/else行为不同_Ruby_Exception_Ruby 1.9_Ruby 1.9.2_Ruby 1.8 - Fatal编程技术网

Ruby 为什么1.9.2和1.8.7中的begin/rescue/else行为不同

Ruby 为什么1.9.2和1.8.7中的begin/rescue/else行为不同,ruby,exception,ruby-1.9,ruby-1.9.2,ruby-1.8,Ruby,Exception,Ruby 1.9,Ruby 1.9.2,Ruby 1.8,我正在使用方法mm。在ruby 1.9.2中,它的行为很奇怪,而不是我得到的预期结果1.9.2=>10 ELSE ** 1.9.2=>8 知道发生了什么吗? class A def mm(data) begin send_len = data return send_len rescue Exception STDOUT.write("Rescue *#{$!}*\n") else STDOUT.write("ELSE *#{

我正在使用方法
mm
。在ruby 1.9.2中,它的行为很奇怪,而不是我得到的预期结果
1.9.2=>10

ELSE **
1.9.2=>8
知道发生了什么吗?

class A

 def mm(data)
   begin
     send_len = data
     return send_len
   rescue Exception
     STDOUT.write("Rescue *#{$!}*\n")
   else
     STDOUT.write("ELSE *#{$!}*\n")
   end
 end

end # class A

a = A.new
print "#{RUBY_VERSION}=>#{a.mm(10)}\n"
使用1.8.7,我得到了预期的结果:

1.8.7=>10
这是一个很好的例子。不过,还有一个讨论,它是应该像1.8中那样,还是像1.9中那样


Ruby的作者Matz.

年读过Dave Thomas等人的《编程Ruby 1.9》一书第355页的“例外情况”,但没有用…@Evgeny Shadchnev为什么在标题中提到1.8.6?我把它改成了1.8.7。@sawa对不起,是打字错误。你是对的。澄清一下,它返回8而不是预期的10的原因是
STDOUT.write(“ELSE*{$!}*\n”)
是实际执行的最后一行(而不是
返回
),并且从中返回值(即写入的字节数,在本例中为8)。谢谢Evgeny。我也这么认为。我以为那是一只虫子…现在我确定了。