Ruby iterators

From wikinotes
Revision as of 15:54, 29 October 2022 by Will (talk | contribs) (→‎Enumerator Functions)
(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

foo = Enumerator.new do |enum|
  var = [1, 2, 3]
  index = 0
  loop do
    break if index >= var.count

    enum.yield(var[index])
    index += 1
  end
end

foo.each { |x| puts x }

Enumerable