1

How can I make an array of 30 min intervals to 8 hours. so this ish:

[30, 60, 90, all-the-way-to,  480]

4 Answers 4

6

You can use a Range and the step method, then convert it to an Array:

(30..480).step(30).to_a

The result is:

[30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360, 390, 420, 450, 480)
Sign up to request clarification or add additional context in comments.

3 Comments

I like this. Another way would be to use an open range and take so you can use it based on how many elements you want. (30..).step(30).take(16).to_a
@vcsjones More flexible but should note that open ranges only work in ruby-2.6.0 and above.
You can use Integer#step, but the calling syntax is a bit different: 30.step(nil, 30).take(16) or 30.step(480, 30).to_a or 0.step(480, 30).drop(1).
2

Your arguments are

increment =  30
duration  = 480 # 8*60

You could use

increment.step(by: increment, to: duration).to_a
  #=> [ 30,  60,  90, 120, 150, 180, 210, 240,
  #    270, 300, 330, 360, 390, 420, 450, 480] 

which reads well. Numeric#step, when used without a block, returns an enumerator, which is why .to_a is needed.

Comments

1

I came up with this, but @infused answer is way better.

a = (1..16).to_a.map{|i| i*30 }

Comments

0

Option selecting (Enumerable#select) from the range:

stop = 480
step = 30

(step..stop).select { |n| n % step == 0 }

#=> [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360, 390, 420, 450, 480]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.