Ruby iterators: Difference between revisions
From wikinotes
No edit summary |
|||
Line 24: | Line 24: | ||
<source lang="ruby"> | <source lang="ruby"> | ||
Enumerator.new do |enum| | foo = Enumerator.new do |enum| | ||
var = [1, 2, 3] | |||
enum.yield | index = 0 | ||
loop do | |||
break if index >= var.count | |||
enum.yield(var[index]) | |||
index += 1 | |||
end | end | ||
end | end | ||
foo.each { |x| puts x } | |||
</source> | </source> | ||
Latest revision as of 15:54, 29 October 2022
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 }