當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Enumerable.lazy用法及代碼示例

本文簡要介紹ruby語言中 Enumerable.lazy 的用法。

用法

lazy → lazy_enumerator

返回一個 Enumerator::Lazy ,它重新定義了大多數 Enumerable 方法以推遲枚舉並僅在 as-needed 基礎上枚舉值。

示例

以下程序查找畢達哥拉斯三元組:

def pythagorean_triples
  (1..Float::INFINITY).lazy.flat_map {|z|
    (1..z).flat_map {|x|
      (x..z).select {|y|
        x**2 + y**2 == z**2
      }.map {|y|
        [x, y, z]
      }
    }
  }
end
# show first ten pythagorean triples
p pythagorean_triples.take(10).force # take is lazy, so force is needed
p pythagorean_triples.first(10)      # first is eager
# show pythagorean triples less than 100
p pythagorean_triples.take_while { |*, z| z < 100 }.force

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Enumerable.lazy。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。