Fixing Range#step

February 13, 2007 code 2 min read

Update: This has been added to Rails’ active_support.

My last post got me thinking about my post a couple months ago about being annoyed that Range\#step requires a block and returns itself.

Well, it’s Ruby. If you don’t like it, change it:

class Range
  alias_method :original_step, :step
  def step(value, &block)
    if block_given?
      original_step(value, &block)
      returning [] do |array|
        original_step(value) {|step| array << step }
(0..10).step(2)                 #=> [0, 2, 4, 6, 8, 10]
(0..10).setp(2) {|i| puts i }   #=> (0..10)

Now, before you start yelling at me for being an irresponsible programmer, may I remind you that this change and the ones in my previous post in no way change the original functionality of Range. step raises an error if no block is given, and include? simply returns false if a range is passed (you can’t have a Range of Ranges, so previously, a range would never include another Range).

I think I may submit a patch for ActiveSupport with these little nuggets.

update: test your code before you publish it. Code has been fixed so it really doesn’t have any adverse side-effects.

This content is open source. Suggest Improvements.


avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.