Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in converting range into Array of floating values in Ruby

Tags:

arrays

range

ruby

How to convert Range having start and end interval as Float values? I am getting error as TypeError: can't iterate from Float

IRB Session

irb(main):058:0> (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

irb(main):059:0> ('a'..'k').to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]

irb(main):061:0> ((1.1)..(1.10)).to_a
TypeError: can't iterate from Float
    from (irb):61:in `each'
    from (irb):61:in `to_a'
    from (irb):61
    .........
like image 354
brg Avatar asked Dec 03 '22 20:12

brg


2 Answers

Try this:

(1.1..1.2).step(0.01).map { |x| x.round(2) }
  # => [1.1, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2]
like image 180
Agis Avatar answered Jan 01 '23 15:01

Agis


You have to specify step you want to iterate with first:

((1.1)..(1.10)).step(0.1).to_a

#=> [1.1]     as range has only one element :)

((1.1)..(1.5)).step(0.1).to_a

# [1.1, 1.2, 1.3, 1.4, 1.5]

Note however it is pretty risky as you might hit float rounding error and the result might look like:

[1.1, 1.2000000000000002, 1.3, 1.4000000000000001, 1.5]

Use BigDecimals to avoid this.

like image 28
BroiSatse Avatar answered Jan 01 '23 17:01

BroiSatse