From: Joe Van Dyk Date: 2005-08-14T09:09:37+09:00 Subject: Re: no clue On 8/13/05, Simon Kr�ger wrote: > > data.each{ |j, line| > k, v = -2, 0 > while (v = line.index(58, k)) > h5[j][line[(k+2)...v].intern] = > line[(v+2)...(k = line.index(44, v) || line.length)] > end > } > > Ok, lets walk this trough: > > j is just the key in the outer hash. > > line looks like: > "x_position: 200, y_position: 400, z_position: 300" > > k is the index of the key (like 'x_position') in the line > v is the index of the value (like '200') in the line > > 58 is the ascii number of the char ':' > 44 is the ascii number of the char ',' > > #index returns the index of the char in the string or nil > if no such char exists (after the index given as second > parameter) > > while there is another ':' in the string > add key from last ',' to ':' => value from ':' to next ',' > end > > the +2 is there to skip the (',' or ':') and the space. > > the initial k = -2 is there because no ',' is there to skip > at the beginning. > > One is loosing readability of code if optimizing for speed > has top priority - even in ruby. > > data.each{|j, line| > line.split(',').each{|kv| > k, v = kv.split(':') > h6[j][k.strip.intern] = v.strip > } > } > > is much nicer, but look at the numbers: > > user system total real > inject 4.672000 0.015000 4.687000 ( 5.281000) > scan 5.250000 0.063000 5.313000 ( 5.312000) > eval 6.140000 0.047000 6.187000 ( 6.219000) > tmp 4.407000 0.062000 4.469000 ( 4.469000) > index 0.375000 0.000000 0.375000 ( 0.375000) > split 10.625000 0.141000 10.766000 ( 10.781000) > true Ah, ok. In my application, there's a bunch more than 3 possible keys and they are of differing length. I am in control of the format of the incoming strings though, and so could modify their format to make them easier/faster to parse. Any ideas on what would be a more efficient format for transporting the data? (for reference, the original string format was "id: 3, x_position: 39, y_position: 209, z_position: 39" and in my real application, there's about twenty different attributes that are in the string.) Perhaps it would be more efficient to not convert the string into a hash? All I really need to be able to do is access/display a player's data via some mechanism, and a player's data should be updated once a second, and there's up to 400 players. The above was the best way I could come up with transporting and accessing the data, but perhaps there's a better way of doing it.