Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Enumerators
Search
Oliver Legg
October 14, 2013
Programming
1
640
Enumerators
Oliver Legg
October 14, 2013
Tweet
Share
More Decks by Oliver Legg
See All by Oliver Legg
Ruby on Rails – A Primer
ollylegg
1
640
Presenters – Take II
ollylegg
1
420
Other Decks in Programming
See All in Programming
PHPで作るWebSocketサーバー ~リアクティブなアプリケーションを知るために~ / WebSocket Server in PHP - To know reactive applications
seike460
PRO
2
760
Запуск 1С:УХ в крупном энтерпрайзе: мечта и реальность ПМа
lamodatech
0
930
はてなにおけるfujiwara-wareの活用やecspressoのCI/CD構成 / Fujiwara Tech Conference 2025
cohalz
0
2k
ISUCON14感想戦で85万点まで頑張ってみた
ponyo877
1
570
Package Traits
ikesyo
1
200
非ブラウザランタイムとWeb標準 / Non-Browser Runtimes and Web Standards
petamoriken
0
430
AppRouterを用いた大規模サービス開発におけるディレクトリ構成の変遷と問題点
eiganken
1
440
Findy Team+ Awardを受賞したかった!ベストプラクティス応募内容をふりかえり、開発生産性向上もふりかえる / Findy Team Plus Award BestPractice and DPE Retrospective 2024
honyanya
0
140
ESLintプラグインを使用してCDKのセオリーを適用する
yamanashi_ren01
2
180
EC2からECSへ 念願のコンテナ移行と巨大レガシーPHPアプリケーションの再構築
sumiyae
3
580
ErdMap: Thinking about a map for Rails applications
makicamel
1
370
watsonx.ai Dojo #6 継続的なAIアプリ開発と展開
oniak3ibm
PRO
0
160
Featured
See All Featured
For a Future-Friendly Web
brad_frost
176
9.5k
Fireside Chat
paigeccino
34
3.1k
It's Worth the Effort
3n
183
28k
YesSQL, Process and Tooling at Scale
rocio
170
14k
How STYLIGHT went responsive
nonsquared
96
5.3k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
59k
Six Lessons from altMBA
skipperchong
27
3.5k
Raft: Consensus for Rubyists
vanstee
137
6.7k
Reflections from 52 weeks, 52 projects
jeffersonlam
348
20k
Rebuilding a faster, lazier Slack
samanthasiow
79
8.8k
Designing on Purpose - Digital PM Summit 2013
jponch
116
7.1k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
29
2.1k
Transcript
ENumerators
Enumerable #all? #any? #chunk #collect #collect_concat #count #cycle #detect #drop
#drop_while #each_cons #each_entry #each_slice #each_with_index #each_with_object #entries #find #find_all #find_index #first #flat_map #grep #group_by #include? #inject #lazy #map #max #max_by #min_by #minmax #minmax_by #none? #one? #partition #reduce #reject #reverse_each #select #slice_before #sort #sort_by #take #take_while #to_a #zip
Enumerator #each #feed #next #next_values #peek #peek_values #rewind #size #with_index
#with_object
enumerator = [1, 2, 3].each # => #<Enumerator: [1, 2,
3]:each> enumerator = [1, 2, 3].to_enum # => #<Enumerator: [1, 2, 3]:each> enumerator = [1, 2, 3].enum_for(:each) # => #<Enumerator: [1, 2, 3]:each>
def counter yield 1 yield 2 yield 3 end enumerator
= enum_for(:counter) enumerator.to_a # => [1, 2, 3]
with_object with_index
letters = ['a', 'a', 'a', 'b', 'b', 'c'] counts =
letters.inject({}) do |memo, letter| memo[letter] ||= 0 memo[letter] += 1 memo end # => {"a"=>3, "b"=>2, "c"=>1}
letters = ['a', 'a', 'a', 'b', 'b', 'c'] counts =
letters.each.with_object({}) do |letter, memo| memo[letter] ||= 0 memo[letter] += 1 end # => {"a"=>3, "b"=>2, "c"=>1}
range = (1..10) range.map.with_index {|n, i| n * i }
# => [0, 2, 6, 12, 20, 30, 42, 56, 72, 90] range.select.with_index {|_, i| i.even? } # => [1, 3, 5, 7, 9]
Iterator
enumerator = [1, 2, 3].each # => #<Enumerator: [1, 2,
3]:each> enumerator.next # => 1 enumerator.next # => 2 enumerator.next # => 3 enumerator.next # StopIteration: iteration reached an end
enumerator = [1, 2, 3].to_enum # => #<Enumerator: [1, 2,
3]:each> enumerator.peek # => 1 enumerator.peek # => 2 enumerator.peek # => 3 enumerator.next # => 1
loop do i = enumerator.next puts i # `loop` silently
rescues StopIteration end
Generator
fibonacci = Enumerator.new(Float::INFINITY) do |yielder| a, b = 0, 1
loop do yielder.yield a a, b = b, (a + b) end end
class SumOfNaturalNumbers < Enumerator def initialize super(Float::INFINITY) do |yielder| n
= 1 loop do yielder.yield (n * (n + 1)) / 2 n += 1 end end end end
def fibonacci a, b = 0, 1 loop do yield
a a, b = b, (a + b) end end enumerator = enum_for(:fibonacci) # => #<Enumerator: main:fibonacci>
LAZY
require 'prime' primes = Prime.instance primes .select {|i| i.to_s.end_with?('3') }
.take(10) # infinite loop
require 'prime' primes = Prime.instance primes .lazy .select {|i| i.to_s.end_with?('3')
} .take(10) .to_a # => [3, 13, 23, 43, 53, 73, 83, 103, 113, 163]
File.open('/usr/share/dict/words') .each_line .lazy .map(&:chomp) .take_while {|line| line.length < 10 }
.to_a
mine = ->(repository) { repository.owner == 'olly' } cutoff =
(Time.now - (365 * 24 * 60 * 60)).to_datetime year_old = ->(repository) { repository.commits.first.date > cutoff } client.repositories .lazy .select(&mine) .select(&year_old) .take(10) .each {|repository| puts repository.name }