Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.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枚举:取第一个n,其中block返回true_Ruby_Enumerable - Fatal编程技术网

Ruby枚举:取第一个n,其中block返回true

Ruby枚举:取第一个n,其中block返回true,ruby,enumerable,Ruby,Enumerable,我想取通过该块的前“n”个条目 a = 1..100_000_000 # Basically a long array # This iterates over the whole array -- no good b = a.select{|x| x.expensive_operation?}.take(n) 一旦我有n个条目,其中“昂贵”条件为真,我想缩短迭代 你有什么建议?花点时间数数n # This is the code i have; which i think can be w

我想取通过该块的前“n”个条目

a = 1..100_000_000 # Basically a long array

# This iterates over the whole array -- no good
b = a.select{|x| x.expensive_operation?}.take(n)
一旦我有n个条目,其中“昂贵”条件为真,我想缩短迭代

你有什么建议?花点时间数数n

# This is the code i have; which i think can be written better, but how?
a = 1..100_000_000 # Basically a long array
n = 20
i = 0
b = a.take_while do |x|
  ((i < n) && (x.expensive_operation?)).tap do |r|
    i += 1
  end
end
#这是我的代码;我认为可以写得更好,但如何写呢?
a=1..100_000_000#基本上是一个长数组
n=20
i=0
b=a.在做x的时候做U|
((i
Ruby 2.0实现,对于较旧版本,请使用gem:


它应该与一个简单的
for
循环和一个
中断一起工作:

a = 1..100_000_000 # Basically a long array
n = 20
selected = []
for x in a
  selected << x if x.expensive_operation?
  break if select.length == n
end
a=1..100_000#基本上是一个长数组
n=20
选定=[]
对于a中的x

已选择在我看来,您的解决方案选择了一些
x
值,即使
x。昂贵的\u操作?
为假。。。这就是你想要的吗?嗯……你是对的,我的解决方案似乎不正确,但不是按照你建议的方式。它将在第一个值处停止,当昂贵的_操作为false时,返回的值小于n。
a = 1..100_000_000 # Basically a long array
n = 20
selected = []
for x in a
  selected << x if x.expensive_operation?
  break if select.length == n
end