Ruby iterators

From wikinotes
Revision as of 20:52, 23 April 2021 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

iterators and codeblocks

Iteration

mylist = ["dog", "cat", "bear"]
mylist.each { |x| puts x }  # print each entry in 'mylist'

Code Blocks

Similar to a function

my_codeblock = { puts "hello" }   # record codeblock
yield my_codeblock                # run codeblock

# unnamed code-block?
do 
  puts "hello"
  puts "you"
end

Enumerator Functions

These are generator functions that yield results

Enumerator.new do |enum|
  for (1..20).each do |i|
    enum.yield i
  end
end

Enumerable