arrays - Ruby 选择方法 : check number of items that are selected

标签 arrays ruby algorithm methods

因此,Ruby 有一个 select 方法,可以根据从 block 中传入的条件从数组中选择元素。

例如

arr = [1,2,3,4]
arr.select {|x| x.even? } => [2, 4]

我的问题涉及一个大数组,我只想选择一定数量的项目。例如,在数组之外,我只想要符合条件的前 5 个数字。

arr.select{|x| x.even?}[0...5]

这就是我目前所拥有的。这非常慢,因为 Ruby 在选取前五个元素之前对整个数组运行 select 函数。

我想看看是否有办法在选择前五个元素时停止选择功能。

例如,如果我能做到这一点

res = arr.select do |x|
  x.even? 
  break if self.length > 5
end

在这种情况下,self 是对 res 数组的引用。我不认为该引用会起作用,但我希望它能表达我的观点。

最佳答案

In this case, self is a reference to the res array.

Ruby 中的关键字 self 使您可以访问当前对象——接收当前消息的对象。

我认为这是一份 Enumerator::Lazy 的工作:

>> (1..100000).lazy.select { |x| x.even? }.first(5)
=> [2, 4, 6, 8, 10]

关于arrays - Ruby 选择方法 : check number of items that are selected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38727336/

相关文章:

arrays - 如何在swift4中使用key访问数组

c - 在 C 中使用指针与数组

c++ - 在多维数组C++问题中检测墙

sql - 为什么 ruby​​ 对字符串数组的排序不同于 sql 顺序(postgres)?

algorithm - 如何在不切割网格几何体的情况下渲染横截面?

php - 数组值字符串编辑和循环与其他数组和循环相结合

ruby-on-rails - 如何在不丢失旧密码的情况下正确地从 has_secure_password 迁移到 encrypted_pa​​ssword(因为两者都使用 password_digest)?

Rails 3.1 中的 JavaScript 单元测试

javascript - 如何反转带数字的字符串,但不要反转 1 和 0?

algorithm - 我需要 NodeMCU 中的 Lua 数学库