Rubyize this: Live in Vancouver. Refactoring #1.

published Jan 27, 2008

At rubycamp today, I ran a little Rubyize This workshop. Rubyize This is a game invented by François Lamontagne. The idea is that someone puts up a chunk of code that is written in Ruby, but in a not very Rubyish way. Then, everyone in the audience gets to Rubyize it!

We tried to use the most excellent RefactorMyCode.com, but the WiFi was too saturated so we had to resort to posting the code on my blog and people plugging their laptops in to the projector to present their results.

So, this post and the following two will show the original code. Keep in mind that this is intentionally ugly!

We had some great refactorings. If you were at the workshop, please post your refactorings in the comments. I’ll make the pretty and put them in the posting.

The other two refactorings are at Rubyize this #2 and Rubyize this #3.

Without further ado, here’s the first refactoring. The code is supposed to create a file filled with random numbers, one number per line.

#!/usr/bin/env ruby

# create num random numbers between min and max 
# and print them to a file called file_name, one per line
def create_random_numbers(file_name, min, max, num)
  file = File.open(file_name, 'w')
  n = 0
  while n < num
    r = rand(max - min) + min
    file.puts(r)
    n += 1
  end
  file.close   
end

create_random_numbers('random.txt', 0, 10, 1000)

Here’s the first refactoring:

def create_random_numbers(file_name, min, max, num) 
  File.open(file_name, 'w') do |f| 
    1.upto(num) {|i| f.puts rand(max-min)+min }
  end 
end

Here’s one from Sam Livingston-Gray

#!/usr/bin/env ruby

# create num random numbers between min and max 
# and print them to a file called file_name, one per line

class Range
  def random_member
    offset = rand(max - min)
    min + offset
  end
end

def create_random_numbers(file_name, range, num)
  File.open(file_name, 'w') do |file|
    num.times { file.puts(range.random_member) }
  end
end

create_random_numbers('random.txt', (0..10), 1000)

Here’s what I came up with:

def create_random_numbers(file_name, min, max, num)
  File.open(file_name, 'w') do |file|
    num.times {file.puts(rand(max - min) + min)}
  end
end

create_random_numbers('random.txt', 0, 10, 1000)
blog comments powered by Disqus