Using a do-end block instead of a proc

In the code hereunder, is there a way to modify the cannel_each method so that it would accept a do-end block instead of expecting a proc ?

# Channel Iterator
def channel_each (c1, f)
    while i = c1.receive?
        f.call(i)
    end 
end

c1 = Channel(Int32).new
c2 = Channel(Nil).new

# sender
spawn do
    (1..10).each do |i|
        sleep(100.milliseconds)
        c1.send(i)
    end
    c1.close
    c2.send nil
end

# receiver
spawn do
    channel_each c1,  ->(i : Int32) {
        puts i
    }
end


c2.receive
puts "Done"

I think instead of f.call(i), you would do yield i and remove the f parameter.

1 Like

Tank you it works :slight_smile:

   
# Channel Iterator
def channel_each (c)
   while item = c.receive?
       yield item
   end 
end

c1 = Channel(Int32).new
c2 = Channel(Nil).new

# sender
spawn do
   (1..10).each do |i|
       sleep(100.milliseconds)
       c1.send(i)
   end
   c1.close
   c2.send nil
end

# receiver
spawn do
   channel_each c1 do |i|
       puts i
   end
end


c2.receive
puts "Done"

1 Like