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 }