红宝石 - 懒洋洋地迭代一个数组 [英] ruby - lazily iterate through an array

查看:124
本文介绍了红宝石 - 懒洋洋地迭代一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历数组的一部分。例如,我尝试打印除第一个元素之外的所有元素:

  array [1 ..- 1] .each {| E |放置e} 

但是 array [1 ..- 1] 生成一个新的 Array 。如果 array 非常庞大,这是很浪费的。另一种直接的方法是:
$ b $ pre $ (1 ... array.size).each {| i | puts数组[i]}

它的工作原理。但是我不知道是否还有一些更优雅的技巧。 解决方案 Ruby 2.0将发布懒惰的枚举(奇妙的消息!),现在我们可以使用像 enumerable-lazy
$ b $ pre $ require'enumerable / lazy'
xs.lazy.drop(1).each {| x |这是不错的,但从概念上说,它不完全适用于你的情况,因为你已经有一个数组,而不是一个懒惰的对象(一个链表),你必须遍历放弃元素(好吧,我们只是丢弃一个元素在这里,它不会成为一个交易断路器)。所以如果你打算使用它的话,你可以将你的解决方案(使用一个范围)抽象为 Enumerable#each_from(start_index)

更多:你也可以为 enumerable-lazy Array#lazy_slice(range)创建一个扩展,一个 Enumerable#lazy 对象。它也看起来不错: xs.lazy_slice(1 ..- 1).each {| x | puts x}


I want to iterate through a part of an array. For example, I try to print every element except the first one:

array[1..-1].each {|e| puts e}

But array[1..-1] builds a new Array. It's wasteful if array is very huge. Another straightforward approach:

(1...array.size).each { |i| puts array[i] }

It works. But I wonder if there are some more elegant tricks.

解决方案

Ruby 2.0 will ship Lazy enumerables (fantastic news!), for now we can warm up the engines using gems like enumerable-lazy:

require 'enumerable/lazy'
xs.lazy.drop(1).each { |x| puts x }

That's not bad, but conceptually it doesn't exactly apply to your case, since you already have an array, not a lazy object (a linked list) that you must traverse to discard elements (ok, we are just discarding one element here, it wouldn't be a deal-breaker). So you could just abstract your solution (that one using a range) as Enumerable#each_from(start_index) if you plan to use it a lot.

More: you could also create an extension to enumerable-lazy Array#lazy_slice(range), which would return a Enumerable#lazy object. It also looks pretty good: xs.lazy_slice(1..-1).each { |x| puts x }

这篇关于红宝石 - 懒洋洋地迭代一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆