def foo
  f = Proc.new { return "return from foo from inside proc" }
  f.call # control leaves foo here
  return "return from foo" 
end

def bar
  b = Proc.new { "return from bar from inside proc" }
  b.call # control leaves bar here
  return "return from bar" 
end

puts foo # prints "return from foo from inside proc" 
puts bar # prints "return from bar" 

我认为return关键字在Ruby中是可选的,无论你是否请求,你总是在输入return.有鉴于此,我发现foobar有不同的输出是令人惊讶的,这是由fooProc f中包含显式return这一事实决定的.

有人知道为什么会这样吗?

推荐答案

Ruby有三种 struct :

  1. block不是一个对象,而是由{...do}...end
  2. proc是由Proc.newproc创建的Proc对象.
  3. lambda是由lambda(或Ruby 1.8中的proc)创建的Proc.

Ruby有三个关键字可以从某物返回:

  1. return终止其所在的方法或lambda.
  2. next终止其所在的块、进程或lambda.
  3. break终止向块屈服的方法或调用其所在的proc或lambda的方法.

在lambdas中,无论出于何种原因,return的行为都类似于next.nextbreak是这样命名的,因为它们最常用于each这样的方法,在each中终止块将导致使用集合的next元素继续迭代,而终止each将导致break退出循环.


If you use return inside the definition of foo, you will return from foo, even if it is inside a block or a proc. To return from a block, you can use the next keyword instead.

def foo
  f = Proc.new { next "return from foo from inside proc" }
  f.call # control leaves foo here
  return "return from foo" 
end
puts foo # prints "return from foo"

Ruby相关问答推荐

Ruby PKCS7:添加;\r〃;字节正在 destruct 解密

令人惊讶的有效 Ruby 语法:% 无处不在

什么是 '?-mix' 在 Ruby 正则表达式中

Ruby 中有内置的二进制搜索吗?

从href html标签中提取带有Ruby中nokogiri的链接(URL)?

将 ruby​​ hash .default 设置为列表

有没有比 Rspec 的 `should_receive` 更少干扰的替代方法?

理解|| Ruby 中 If 条件中的 OR 运算符

如何绘制 git repo 的代码行历史记录?

Puppet/Facter无法检索事实 fqdn:如何修复或规避?

理解 Ruby 中的私有方法

rbenv、rvm 和 chruby 有什么区别?

ruby 中&:运算符的功能是什么?

Ruby 方法to_sym有什么作用?

Ruby 中的=~运算符是什么?

Ruby中的urldecode?

Ruby 中的 to_s 与 to_str(以及 to_i/to_a/to_h 与 to_int/to_ary/to_hash)

如何在 gemspec 中指定最低 Ruby 版本?

我更改存储库 URL 后 Capistrano 部署失败

带有类名的动态类定义