From: Eric Hodel Date: 2005-11-09T05:46:31+09:00 Subject: Re: Better way to build string On Nov 8, 2005, at 11:00 AM, Eero Saynatkari wrote: > marcus wrote: >> I'm trying to build a query string based on an array of >> properties. Is there a shorter/nicer way to do the following? >> def build_query_string(properties, prop_type) >> result = "" >> properties.each do |item| >> if prop_type == "tag" >> result += " #{item.name}=#{item.value}" >> else >> if result == "" >> result = "?" >> else >> result += "&" >> end >> result += "#{item.name}=#{item.value}" >> end >> end >> result >> end > > Perhaps you can modify this for your needs: > > properties.inject('?') {|memo, (key, value)| memo << "#{key}=# > {value}&" } "?" + properties.map { |pair| pair.join('=') }.join('&') Shorter, more expressive, omits the trailing '&' -- Eric Hodel - drbrain@segment7.net - http://segment7.net FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04