Iterating in Ruby

Another Ruby cheat sheet, this time for iterating.

Basic Iteration

A simple loop can be achieved with a for, a while, each, step or an until… note that in the below, the result will always be the numbers 1,2,3,4,5 being “puts” to the screen.

  for i in 1..5 do
    puts i
  end
  (1..5).each do
  	|num| puts num
  end
  1.step(5) { |i| puts i }
  i = 1
  while i <= 5 do
  	puts i
  	i += 1
  end
  i = 1
  begin
  	puts i
  	i += 1
  end while i <= 5
  i = 1
  until i > 5 do
  	puts i
  	i += 1
  end
  i = 1
  begin
  	puts i
  	i += 1
  end until i > 5

The “while” looks fairly traditional – you can include parenthesis in the conditional if you want but like many places in Ruby they are optional. “Until” is a little unorthodox from a programming language perspective… you’ll notice there are two variations of both the “while” and the “until”. I imagine these variations exist to cater for the various ways that developers brains are wired/broken, but personally I am loving the ability to write code the way I want to, not the way the syntax wants me to.

The rest of them should be fairly self explanatory, if also a little unusual looking. If you haven’t seen the “1..5” notation before, it’s a ruby “Range” object representing the numbers 1 to five. You can assign these to variables too, so you could just as easily go;

  x = 1..5
  for i in x do
    puts i
  end

The “each” and “for” methods will also work on arrays (e.g. [1,2,3,4,5]). Incidentally, it’s worth pointing out that there is no “traditional-looking” equivalent the “for” syntax – it’s less syntactic sugar and more a syntactic enema.

Iterate by more than 1

If you wanted the Ruby equivalent of the following;

   for(int i = 1; i < 10; i += 2)

It can be achieved by passing a second argument to the “step” method like so;

1.step(10,2) { |i| puts i }

Which would translate to “start at 1, stop at 10, go up by 2 each time”. This is probably the neatest way to explain here, but you can obviously achieve the same with the while / until syntax (just increment your iterator by +=2 instead of +=1). It all depends on your own context.

Breaking etc..

For anyone coming to Ruby from a C# / C++ background like me, these equivalents exist;

 break       #break out of the loop
 next        #equivalent to C#'s 'continue', starts the next iteration
 redo        #starts the iteration again
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s