Archive

Archive for January 29th, 2010

exception iteration in ruby

January 29th, 2010 Comments off

There are many ways to iterate in ruby, many methods, but going back to assembler roots of mine I found another one:

>> a=[1,2,3]
=> [1, 2, 3]
>> begin puts a.shift; raise unless a.blank?; rescue; retry; end
1
2
3
=> nil

This code is only prof of concept, it should not be used for iterations, by example if it would be used without prior initialization of “a” variable it would be an endless loop as on exception “NameError” it will retry in endless loop.

There are other places where this could be used, but even possible retry should not be used without some kind of endless loop protection like:

>> i=10; begin puts IO.read('some.file'); rescue; if i>0 then puts "#{i} ..."; i-=3; sleep 1; retry; end; end
10 ...
9 ...
8 ...
7 ...
some file created
=> nil

In this example a file was created during run of the command – on second console by just running “echo some file created > some.file”.

There are other ways to do the same, maybe not so cool like that above but probably most of developers will prefer something like:

>> 10.downto(1){|i| begin puts IO.read('some.file'); break; rescue; puts "#{i} ..."; sleep 3; end }
10 ...
9 ...
8 ...
some file created
=> nil

Did You liked this post or maybe not, vote on it at dzone.

Categories: Development Tags: , , ,