Home on the Range

Posted on August 16, 2007
Happened upon some old code that I wrote in a hurry:
1.upto(@areas.size) do |j|
  ranks << j
end

Was simply trying to build an array of integers from 1 to @areas.size. This is Ruby though, there’s almost always a cleaner / more elegant way to do things.

Enter the Range class and it’s to_a method. Ranges simply represent a range of numbers, with a few handy helper methods.

range = 1..5
range.class # Range
range.to_a # [1, 2, 3, 4, 5]
Refactoring the original code to use a Range one-liner:
ranks = (1..@areas.size).to_a   # build an array [1, 2 ... to @areas.size]

There are many other ways to do this in Ruby as well. Codegolf anyone?