Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about ruby range?

Tags:

each

range

ruby

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
like image 453
why_ Avatar asked Apr 06 '10 09:04

why_


People also ask

How do you find the range in Ruby?

There are two methods you can use when working with Ruby ranges. These are the include and the cover. The include method works by checking if a value is in the range, while the cover checks the initial and ending value of the range for a match.

How do I print a range in Ruby?

You can cast your range (in parentheses) to an array ([1 2 3 4 5 6... 48 49 50]) and join each item (e.g. with ' ' if you want all items in one line).

What is step in Ruby?

Stepping is the process of controlling step-by-step execution of the program.


1 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 image 143
Amber Avatar answered Sep 18 '22 12:09

Amber