Is this your first visit? You may want to subscribe to the feed.

Why does #step return itself?

update: problem solved!

Today, I wanted to get an array of numbers from 5 to 250, incrementing by 5. You’d think this would be a perfect job for Range#step or Number#step, but strangely enough, both of them return self:

(5..250).step(5) { } #=> 5..250
5.step(250, 5) { } #=> 5

I cannot figure out why in the world step would return self. The other annoyance is that step must receive a block, but, given it’s return value, I understand why.

So, to accomplish my original goal, I could make use of #step by creating a temporary variable:

result = []
(5..250).step(5) {|n| result << n }

But, it feels unnatural in Ruby to create temporary variables, so I ended ditching #step:

(5..250).select {|n| n % 5 == 0 }
Code: range, ruby Dec 11, 2006 ● updated Feb 13, 2007 3 comments

3 comments

  1. Ouch! It’s a lil’ idiom in Ruby for all iterators to return the item iterated upon so you can chain them. That being said, you’re right—it’d be nice if step had a blockless form that returned the step’d array it would normally each over.

    Chris Chris December 12, 2006 at 01:17 AM
  2. Even if everybody agrees, it’ll never be changed due to ‘historical’ reasons :-(

    Hendy Irawan Hendy Irawan December 12, 2006 at 02:25 AM
  3. Hendy: I know, I just wanted to complain about it. :)

    Brandon Brandon December 12, 2006 at 09:09 AM

Speak your mind:

*

*


* I hate spam and will never sell or publish your email address.

(You may use textile in your comments.)

Subscribe

Browse by Tag