From: Robert Klemme Date: 2011-03-30T18:09:20+09:00 Subject: Re: Why can a floating point number be used as an array index? On Tue, Mar 29, 2011 at 10:02 PM, Sniper Abandon wrote: > Jeff Dik wrote in post #989828: >> Why can a floating point number be used as an array index?  Anybody >> know of a good use case for this? >> >> irb(main):020:0> [1, 2, 3][0.3] >> 1 >> irb(main):021:0> [1, 2, 3][0.9] >> 1 > arr = [1,2,3,4....] > arr[(anyhting).to_i] No, it's using #to_int irb(main):001:0> idx = Object.new => # irb(main):002:0> %w{foo bar}[idx] TypeError: can't convert Object into Integer from (irb):2:in `[]' from (irb):2 from /opt/bin/irb19:12:in `
' irb(main):003:0> class < def to_i;p "to_i";1;end irb(main):005:1> end => nil irb(main):006:0> %w{foo bar}[idx] TypeError: can't convert Object into Integer from (irb):6:in `[]' from (irb):6 from /opt/bin/irb19:12:in `
' irb(main):007:0> class < def to_int;p "to_int";1;end irb(main):009:1> end => nil irb(main):010:0> %w{foo bar}[idx] "to_int" => "bar" #to_i is just a convenience conversion (e.g. String#to_i) while #to_int is only used for things which *are* actually an integer. You can see all implementators with "ri '#to_int'". Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/