while expression do program end
do
that follows the expression
is optional. Often you will also see this:while expression program end
irb
example:$ irb --simple-prompt >> i = 0 => 0 >> while i < 3 do ?> puts i >> i = i + 1 >> end 0 1 2 => nil >> exit $
until expression program end
irb
example:$ irb --simple-prompt >> i = 5 => 5 >> until i == 0 >> i = i - 1 >> puts i >> end 4 3 2 1 0 => nil >> exit $
5.times { |i| puts i }
i
is the iterator and puts i
is the
block.5.times do |i| puts i end
Fixnum
has
the iterator times
. Let's see what help
ri
offers us:$ ri -T Fixnum.times Fixnum.times (from ruby site) Implementation from Integer ------------------------------------------------------------------------------ int.times {|i| block } -> self int.times -> an_enumerator ------------------------------------------------------------------------------ Iterates block int times, passing in values from zero to int - 1. If no block is given, an enumerator is returned instead. 5.times do |i| print i, " " end produces: 0 1 2 3 4 $
$ irb --simple-prompt >> 5.times do |i| ?> puts i >> end 0 1 2 3 4 => 5 >> exit $
$ irb --simple-prompt >> 5.times { |i| puts i } 0 1 2 3 4 => 5 >> exit $
$ irb --simple-prompt >> 5.times { puts 'example' } example example example example example => 5 >> exit $
times
there is also the
method upto
, for easily implementing a
loop. ri
offers a nice example for this,
too:$ ri -T Fixnum.upto Fixnum.upto (from ruby site) Implementation from Integer ------------------------------------------------------------------------------ int.upto(limit) {|i| block } -> self int.upto(limit) -> an_enumerator ------------------------------------------------------------------------------ Iterates block, passing in integer values from int up to and including limit. If no block is given, an enumerator is returned instead. 5.upto(10) { |i| print i, " " } produces: 5 6 7 8 9 10 $
Updates about this book will be published on my Twitter feed.