Array of numbers and half numbers in Ruby

I am trying to fill an array with dimensions that are measured by integers and half numbers (i.e. 10, 10.5, 11, 11.5, 12). So far I:

(10..12).map{ |size| [size, size + 0.5] }.flatten[0...-1] 

Is there a more eloquent way to do this in Ruby without having to smooth and remove the last element?

+7
ruby
source share
3 answers

My personal favorite:

 >> (10..12).step(0.5).to_a => [10.0, 10.5, 11.0, 11.5, 12.0] 
+14
source share

You can use lambdas (note that it throws floats). I will let you decide if this is more eloquent.

 irb(main):001:0> fn = ->(x, y) { (x*2..y*2).map { |i| i / 2.0 } } => #<Proc: 0x007fa782b0a4b0@ (irb):1 (lambda)> irb(main):002:0> fn.call(10, 12) => [10.0, 10.5, 11.0, 11.5, 12.0] 
0
source share

I suggested that you want the values โ€‹โ€‹in the returned array to alternate between Fixnum and Float , as in your example:

 (10..12).flat_map { |size| [size, size + 0.5] }.tap { |a| a.pop } #=> [10, 10.5, 11, 11.5, 12] 
0
source share

All Articles