so I am trying to understand code blocks and iterators with this simple exercise, and ran into an issue using brackets that I don't understand.
I have a 'my_times' method
class Integer
def my_times
c = 0
until c == self
yield(c) # passes 'c' to code block
c += 1
end
self # return self
end
end
5.my_times {|i| puts "i'm on MY iteration #{i}"}
which works fine, then I have a 'my_each2' that operates as it should
class Array
def my_each2
size.my_times do |i| # <-- do signifies a code block correct? 'end' is unnecessary?
yield self[i]
end
self
end
end
array.my_each2 {|e| puts "MY2 block just got handed #{e}"}
from my understanding the 'do |i|' in "size.my_times do |i|" is a code block (with no 'end'?) correct?
if so, then why do I get an error trying to put it in {brackets} instead of using 'do'?
class Array
def my_each3
size.my_times {|i| puts "i'm on MY iteration #{i}"} # <-- error here
yield(self[i])
end
self
end
end
array.my_each3 {|e| puts "MY3 block just got handed #{e}"}
but using a 'do' works
size.my_times do |i| puts "i'm on MY iteration #{i}"