简体   繁体   English

在Ruby中,“块出来的收益”是什么意思?

[英]What does 'yield called out of block' mean in Ruby?

I'm new to Ruby, and I'm trying the following: 我是Ruby的新手,我正在尝试以下方法:

mySet = numOfCuts.times.map{ rand(seqLength) }

but I get the 'yield called out of block' error. 但是我得到了“收益率被阻止”的错误。 I'm not sure what his means. 我不确定他的意思。 BTW, this question is part of a more general question I asked here . 顺便说一下,这个问题是我在这里提出的一个更普遍的问题的一部分。

The problem is that the times method expects to get a block that it will yield control to. 问题是,times方法期望得到一个它将产生控制权的块。 However you haven't passed a block to it. 但是你还没有传递一个块。 There are two ways to solve this. 有两种方法可以解决这个问题。 The first is to not use times: 首先是不使用时间:

mySet = (1..numOfCuts).map{ rand(seqLength) }

or else pass a block to it: 或者传递一个块到它:

mySet = []
numOfCuts.times {mySet.push( rand(seqLength) )}

if "numOfCuts" is an integer, 如果“numOfCuts”是一个整数,

5.times.foo   

is invalid 是无效的

"times" expects a block. “时代”期待一个阻止。

5.times{   code here   } 

You're combining functions that don't seem to make sense -- if numOfCuts is an integer, then just using times and a block will run the block that many times (though it only returns the original integer: 你正在组合似乎没有意义的函数 - 如果numOfCuts是一个整数,那么只使用次数和一个块将多次运行该块(尽管它只返回原始整数:

irb(main):089:0> 2.times {|x| puts x}
0
1
2

map is a function that works on ranges and arrays and returns an array: map是一个适用于范围和数组并返回数组的函数:

irb(main):092:0> (1..3).map { |x| puts x; x+1 }
1
2
3
[2, 3, 4]

I'm not sure what you're trying to achieve with the code - what are you trying to do? 我不确定你要用代码实现什么 - 你想做什么? (as opposed to asking specifically about what appears to be invalid syntax) (而不是具体询问看似无效的语法)

Bingo, I just found out what this is. 宾果,我刚刚发现了这是什么。 Its a JRuby bug. 它是一个JRuby错误。

Under MRI 在MRI下

>> 3.times.map
=> [0, 1, 2]
>> 

Under JRuby 在JRuby下

irb(main):001:0> 3.times.map
LocalJumpError: yield called out of block
    from (irb):2:in `times'
    from (irb):2:in `signal_status'
irb(main):002:0> 

Now, I don't know if MRI (the standard Ruby implementation) is doing the right thing here. 现在,我不知道MRI(标准的Ruby实现)是否在这里做正确的事情。 It probably should complain that this does not make sense, but when n.times is called in MRI it returns an Enumerator, whereas Jruby complains that it needs a block. 它可能应该抱怨这没有意义,但是当在MRI中调用n次时它返回一个枚举器,而Jruby则抱怨它需要一个块。

Integer.times expects a block. Integer.times需要一个块。 The error message means the yield statement inside the times method can not be called because you did not give it a block. 错误消息表示无法调用times方法中的yield语句,因为您没有给它块。

As for your code, I think what you are looking for is a range: 至于你的代码,我认为你要找的是一个范围:

(1..5).map{ do something }

Here is thy rubydoc for the Integer.times and Range . 这里是你的rubydoc Integer.times范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM