iterator - Ruby, error with brackets for code block -
so trying understand code blocks , iterators simple exercise, , ran issue using brackets don't understand.
i have 'my_times' method
class integer def my_times c = 0 until c == self yield(c) # passes 'c' code block c += 1 end self # return self end end 5.my_times {|i| puts "i'm on iteration #{i}"}
which works fine, have 'my_each2' operates should
class array def my_each2 size.my_times |i| # <-- signifies code block correct? 'end' unnecessary? yield self[i] end self end end array.my_each2 {|e| puts "my2 block got handed #{e}"}
from understanding 'do |i|' in "size.my_times |i|" code block (with no 'end'?) correct?
if so, why error trying put in {brackets} instead of using 'do'?
class array def my_each3 size.my_times {|i| puts "i'm on iteration #{i}"} # <-- error here yield(self[i]) end self end end array.my_each3 {|e| puts "my3 block got handed #{e}"}
but using 'do' works
size.my_times |i| puts "i'm on iteration #{i}"
the 'do |i|' in "size.my_times |i|" code block (with no 'end'?) correct?
no, not. do ... end
code block.
if so, why error trying put in {brackets} instead of using 'do'?
since condition not satisfied, question trivially satisfied.
Comments
Post a Comment