opensoul.org

Fixing Range#step

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)
    else
      returning [] do |array|
        original_step(value) {|step| array << step }
      end
    end
  end
end
(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.

range and ruby February 13, 2007

1 Comment

  1. Zach Dennis Zach Dennis February 14, 2007

    I like this alot. This should not just go into ActiveSupport, I think this should be submitted as an RCR. http://rcrchive.net/

Post a Comment

Comments use textile. Anonymous comments will be deleted.

My name is Brandon Keepers. I like to build things, usually in Ruby or JavaScript. I work at GitHub and live in Holland, MI.

Popular Posts