-2

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}"
user1297102
  • 661
  • 8
  • 14

2 Answers2

-1

the 'do |i|' in "size.my_times do |i|" is a code block (with no 'end'?) correct?

No, it is not. do ... end is a code block.

if so, then why do I get an error trying to put it in {brackets} instead of using 'do'?

Since the condition is not satisfied, the question is trivially satisfied.

sawa
  • 165,429
  • 45
  • 277
  • 381
-2

'do |i|' IS a code block, the 'end' is a few lines down from it.

the complete block is

size.my_times do |i|     
    yield self[i]
end

so the correct bracketed version is

size.my_times { |i|  yield(self[i]) }

ok move on, nothing to see here :p

user1297102
  • 661
  • 8
  • 14