about ruby range?

like this

range = (0..10)

how can I get number like this:

0 5 10 

plus five every time but less than 10

if range = (0..20) then i should get this:

0 5 10 15 20

Answers


Try using .step() to go through at a given step.

(0..20).step(5) do |n|
    print n,' '
end

gives...

0 5 10 15 20

As mentioned by dominikh, you can add .to_a on the end to get a storable form of the list of numbers: (0..20).step(5).to_a


Like Dav said, but add to_a:

(0..20).step(5).to_a # [0, 5, 10, 15, 20]

The step method described in http://ruby-doc.org/core/classes/Range.html should do the job but seriously harms may harm the readability.

Just consider:

(0..20).step(5){|n| print ' first ', n }.each{|n| print ' second ',n }

You may think that step(5) kind of produces a new Range, like why_'s question initially intended. But the each is called on the (0..20) and has to be replaced by another step(5) if you want to "reuse" the 0-5-10-15-20 range.

Maybe you will be fine with something like (0..3).map{|i| i*5}?

But "persisting" the step method's results with .to_a should also work fine.


Need Your Help

Adding Attribute to JAR's Manifest Via ANT TASK

java ant jar

all i am stuck with an issue. I have 14 third party jars.I am signing those jars with comodo code sign certificate successfully via ant task.

How to enable the video output on your iPad app?

video ipad out

Just found out that the video output of the iPad is not a system level functionality, but that it needs to be explicitly build in into each app.