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
.........
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With