From: Michael Edgar Date: 2011-03-30T05:36:36+09:00 Subject: Re: Why can a floating point number be used as an array index? Keep in mind that arrays use the implicit integer conversion protocol, #to_int, to make this conversion. You can't use any old object with #to_i: >> [1, 2, 3]["1"] TypeError: can't convert String into Integer Very few classes implement this protocol: >> ObjectSpace.each_object { |a| p(a) if Module === a && a.instance_methods(false).include?(:to_int) } Float Integer Numeric I suspect the primary reason for allowing Arrays to convert floats to appropriate indices is to simplify calculated array indices in *any* case. Sam gives a good example, but there are even more common, simple cases where one might calculate array indices and not want to have to call #to_i every time. Here's one for determining what item in a list was clicked: chosen_item = items[ pixel_clicked.y / item_size ] Michael Edgar adgar@carboni.ca http://carboni.ca/ On Mar 29, 2011, at 4:17 PM, Sam Duncan wrote: > How about statistical bucketing. Imagine your indexes 1, 2, and 3 are Gb of RSS or something. > > > irb > ruby-1.9.2-p0 > rss = [0.123, 1.223, 5.33, 2.294, 7.66, 5.6, 3.222, 3.88, 3.44, 1.78] # incoming rss values > => [0.123, 1.223, 5.33, 2.294, 7.66, 5.6, 3.222, 3.88, 3.44, 1.78] > > ruby-1.9.2-p0 > buckets = (0..rss.max).collect {|i| i} # bucket indexes > => [0, 1, 2, 3, 4, 5, 6, 7] > > ruby-1.9.2-p0 > rss.reduce(Hash.new(0)) {|h, v| h.tap{|h| h[buckets[v]]+=1}} # statistics! > => {0=>1, 1=>2, 5=>2, 2=>1, 7=>1, 3=>3} > > I'm sure there are lots of (probably simpler) ways to do the same thing, but it was a fun exercise nonetheless =] > > Sam > > > On 30/03/11 07:35, Jeff Dik wrote: >> 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 >> >> Just curious, >> Jeff >> >> >