Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Enumerators
Search
Oliver Legg
October 14, 2013
Programming
770
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Enumerators
Oliver Legg
October 14, 2013
Transcript
22 slides
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 }
More Decks by Oliver Legg
See All by Oliver Legg
Ruby on Rails – A Primer
ollylegg
1
760
Presenters – Take II
ollylegg
1
520
Other Decks in Programming
See All in Programming
はじめてのPLATEAU
nokonoko1203
1
670
LLM 101: Exploring LLMs, Starting with Tokens.
dalinaum
0
120
RaspberryPi 5で軽くはじめるk3sとtailscaleを用いたホームサーバー構築 (1)
nasum
0
440
AIエージェントの「テストは通るのに本番で壊れる」を減らす
shibuiwilliam
3
130
선언형 햅틱 라이브러리 진동을 소개합니다
l2hyunwoo
1
330
AIコーディングをセッションで終わらせない: PHPライブラリ開発におけるコンテキスト承継設計
ickx
0
110
自宅サーバはどこまで再現できるのか - Proxmox VE上のVM環境をIaCとバックアップで戻してみた
youto
0
450
止まらない比較を止める — 余帰納法で無限ストリームを比べる
tarao
0
220
マルチプロダクトSaaSの アプリ一覧を速くする——複数プロダクトにまたがる「権限行脚」を減らすまで #techramen26conf
mktakuya
1
240
AI駆動TDD ― 2026年10月版
hrmstrsmgs
0
110
JavaScriptはシングルバイナリの夢を見るか / Does JavaScript Dream of a Single Binary?
ssssota
0
450
例外からRich Errorsまで Kotlinエラーハンドリングの進化を読み解く
shiita0903
0
250
Featured
See All Featured
Build The Right Thing And Hit Your Dates
maggiecrowley
39
3.5k
Ten Tips & Tricks for a 🌱 transition
stuffmc
1
290
Conquering PDFs: document understanding beyond plain text
inesmontani
PRO
4
3.3k
Mind Mapping
helmedeiros
1
460
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
650
A designer walks into a library…
pauljervisheath
211
25k
Typedesign – Prime Four
hannesfritz
42
3.2k
The Hidden Cost of Media on the Web [PixelPalooza 2025]
tammyeverts
2
590
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
8.4k
Bootstrapping a Software Product
garrettdimon
PRO
306
120k
The Curse of the Amulet
leimatthew05
4
17k
Lessons Learnt from Crawling 1000+ Websites
charlesmeaden
PRO
1
1.8k