Enumerator yielder.yield 与 Proc.yield 区别

最近看ruby cookbook遇到这个用法,google一下,这里原文解释

http://stackoverflow.com/questions/18865860/enumerator-yielder-yield-vs-proc-yield

 

Enumerator yielder.yield VS Proc.yield

The yield statement has no receiver. Inside a method it means "Run the block right now". An error occurs if no block is attached. It is not always given an argument, because sometimes you just want to run the block.

就是说。有时候未必会传递一个block。仅仅是想运行一个block。但是未必会传递这个block,这时yielder.yield派上用场

例如

def foo
yield :bar
end
foo # LocalJumpError
foo { |x| puts x } # bar

Enumerator::Yielder
For a yielder, yield is almost always given an argument. That's because it means the same as << which is "The next time someone calls next on me, give them this value".

yield总是会得到一个参数, 因为<<和yield一样意思,下一次在我身上调用next方法,返回这个值

Enumerator.new { |yielder| yielder.yield 3 }.next # 3 #返回3
Enumerator.new { |yielder| yielder << 3 }.next # same thing

Proc
Procs and lambdas are basically functions. yield here means the same thing as call, which "Just call the function". You can give it an argument or not, depending on how the proc was defined. Nothing fancy here.

procs和lambda类似函数,yield和call作用一样,调用这个函数 你可以传递或者不传递参数,这个传不传按照proc怎么定义来看,
proc { |x| puts x }.yield(:bar) # bar
proc { |x| puts.x }.call(:bar) # same thing

转载于:https://www.cnblogs.com/or2-/p/5116524.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值