Bob Nadler, Jr. Bob Nadler, Jr.

Faking Data with Ranges in Ruby

Published almost 14 years ago less than 1 min read

On a recent project I needed to create some fake data for some reporting screens. I was using StaticMatic to generate a mockup site and decided to try out the Faker gem for creating the data. Faker worked out well, but it doesn't have any support for generating numerical data.

Generating a random number in Ruby is easy with Kernel::rand, but I wanted to generate numbers within a certain range. My first attempt resulted in a helper method like this:

I had the feeling that this was an inelegant solution, but I wasn't sure of a better approach, so I just moved on. Later that day it hit me: why not use a Range object? So I re-opened the Range class and added this method:

The cool part is that this will not only pull a random number from a number range but it also should work with other types of ranges like dates, for example.


Share This Article