Dhanu Gurung
Dhanu Gurung

Reputation: 8840

Error in converting range into Array of floating values in 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
    .........

Upvotes: 4

Views: 2074

Answers (4)

Agis
Agis

Reputation: 33626

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]

Upvotes: 7

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

For example:

(1.1..1.2).step(0.01).to_a
# => [1.1, 1.11, 1.12, 1.1300000000000001, 1.1400000000000001, 1.1500000000000001, 1.1600000000000001, 1.1700000000000002, 1.1800000000000002, 1.1900000000000002, 1.2]

Hither you shell to convert Range into Enumerator, which could be transformed into an Array with #to_a method.

Upvotes: 4

BroiSatse
BroiSatse

Reputation: 44675

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.

Upvotes: 4

Arup Rakshit
Arup Rakshit

Reputation: 118261

Read Custom Objects in Ranges

Ranges can be constructed using any objects that can be compared using the <=> operator. Methods that treat the range as a sequence (#each and methods inherited from Enumerable) expect the begin object to implement a succ method to return the next object in sequence. The step and include? methods require the begin object to implement succ or to be numeric.

This will give you the idea, about what are factors made Ruby to throw you that error.

Upvotes: 3

Related Questions