Robert Klemme
2/8/2007 8:44:00 PM
On 08.02.2007 20:42, Luke Ivers wrote:
> I'm going to cross-post this from the Rails group, because some of the
> people here are Ruby ninjas and don't read that forum, and I'd like help
> getting this function optimized... its results are useful in a Rails
> perspective, but it's functionality has nothing to do with Rails at all.
>
> class Hash
> def to_params(parent = '')
> ret = ''
> self.keys.each do |key|
> if self[key].is_a? Hash
> if parent == ''
> ret += self[key].to_uri(key.to_s)
> else
> ret += self[key].to_uri(parent + "[#{key.to_s}]")
> end
> else
> if parent == ''
> ret += "#{key}=#{self[key]}&"
> else
> ret += "#{parent}[#{key}]=#{self[key]}&"
> end
> end
> end
> return ret.chomp('&')
> end
> end
>
> Anybody got any optimizations(either quicker speed, or less text and
> comparable speed) for that one?
Use << instead of += in all places.
replace the line
self.keys.each do |key|
with
each do |key, value|
Replace "self[key]" with "value" then.
Maybe change the major if then else with case when end in order to more
easily adjust to special treatment of other types than Hashes.
If you need more efficiency improvements, extract the "if parent=''"
from the loop, make it a top level decision and have two iterations (if
and else branch).
And, make the string / stream to append to a parameter. That way you
don't need to create potentially large strings during recursion before
you append them but you can directly append - you basically just have one.
Typing left as an exercise for the reader. :-)
Kind regards
robert