From: "Simon Kröger" Date: 2005-08-13T06:53:33+09:00 Subject: Re: no clue This may not be exactly an improvement but at least ..hmm.. funny? -------------------------------------------------------------- a = [[0, "x_position: 20, y_position: 40, z_position: 30"], [1, "x_position: 20, y_position: 40, z_position: 30"]] h = eval('{' + ("~" + a.join("~")). gsub(/\s*([^:\~|]+):\s*([^,~]+),?/, ':\1=>\'\2\','). gsub(/~(\d+)~/, '},\1=>{')[2..-2]+ '}}') puts h[1][:y_position] -------------------------------------------------------------- cheers Simon Joe Van Dyk wrote: > On 7/1/05, Daniel Brockman wrote: > >>Joe Van Dyk writes: > > > (original attempt.. was too slow) > > >>> attributes = message.split(",") >>> attributes.each do |attribute| >>> key, value = attribute.scan(/(\w+): (.+)/)[0] >>> result_hash[key.to_sym] = value.strip >>> end >> >>How about this? >> >> message.scan /(\w+)\s*:\s*([^, ]*)/ do |k, v| >> result_hash[k.to_sym] = v end >> >> >>>Also, this will get ran potentially thousands of times per second, >>>so executation speed is of some concern. >> >>I don't know if the above is the best you can do, but I do believe it >>is a bit faster than your original version. > > > Bringing up an old thread.... I have the following code. > > # Converts an array like > # [[0, "x_position: 20, y_position: 40, z_position: 30"], > # [1, "x_position: 20, y_position: 40, z_position: 30"] > # ] > # > # into a hash like > # { 0 => { :x_position => "20", :y_position => "40", :z_position => "30" }, > # 1 => { :x_position => "20", :y_position => "40", :z_position => "30" } > # } > def self.convert_message_to_hash players_array > raise "Can't do anything with empty message!" if original_message.nil? > result_hash = {} > original_message.each do |id, message| > message.scan(/(\w+)\s*:\s*([^, ]*)/) do |k, v| > result_hash[id][k.to_sym] = v > end > end > result_hash > end > end > > That code in my application leads to the following profiling: > % cumulative self self total > time seconds seconds calls ms/call ms/call name > 37.84 261.23 261.23 5569 46.91 69.61 String#scan > 8.12 317.28 56.05 201791 0.28 0.28 Hash#[] > 6.42 409.72 44.31 150783 0.29 0.29 Hash#[]= > 6.36 453.61 43.89 144782 0.30 0.30 String#to_sym > > I believe this is probably the critical part of my code. > > Ideas on how to improve this would be appreciated! > >