4

How can one create an array filled with values within a range (having a begin and end value) and a step? It should support begin and end values of float type.

Jeehut
  • 20,202
  • 8
  • 59
  • 80
  • If you are looking on how to do this with integer values only, see http://stackoverflow.com/questions/2583665/about-ruby-range or http://stackoverflow.com/questions/3029785/declaring-an-integer-range-with-step-1-in-ruby and simply call `.to_a` at the end. – Jeehut Aug 26 '15 at 08:45
  • Why `decimal` and not just `float`? I think that's confusing since Ruby has `BigDecimal` as decimal data type. – cremno Aug 26 '15 at 09:01
  • @cremno: You're right, I'm updating the wording to only state `float` then. – Jeehut Aug 26 '15 at 12:34

1 Answers1

6

For floats with custom stepping you can use Numeric#step like so:

-1.25.step(by: 0.5, to: 1.25).to_a
# => [-1.25, -0.75, -0.25, 0.25, 0.75, 1.25] 

If you are looking on how to do this with integer values only, see this post or that post on how to create ranges and simply call .to_a at the end. Example:

(-1..1).step(0.5).to_a
# => [-1.0, -0.5, 0.0, 0.5, 1.0] 
Community
  • 1
  • 1
Jeehut
  • 20,202
  • 8
  • 59
  • 80
  • btw, posting the question if you know the answer, not sure it's in the spirit of SO.... – tomsoft Aug 26 '15 at 08:35
  • 3
    It sure is in the spirit of SO, it's even encouraged to do so, see this post on meta: http://meta.stackexchange.com/questions/17463/can-i-answer-my-own-questions-even-if-i-knew-the-answer-before-asking – Jeehut Aug 26 '15 at 08:36
  • Oh. Makes sense, actually. – Borsunho Aug 26 '15 at 08:39