opensoul.org

Why does #step return itself?

December 12, 2006 code 2 min read

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 }
This content is open source. Suggest Improvements.

@bkeepers

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.