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 }
3 comments
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
stephad a blockless form that returned the step’d array it would normallyeachover.Even if everybody agrees, it’ll never be changed due to ‘historical’ reasons :-(
Hendy: I know, I just wanted to complain about it. :)
Speak your mind: