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
I always find it useful to post code that is runnable
by copy+paste so people trying to help me don't have
to implement all the helper stuff first.
···
--- Ursprüngliche Nachricht ---
Von: marcus <m-lists@bristav.se>
An: ruby-talk@ruby-lang.org (ruby-talk ML)
Betreff: Better way to build string
Datum: Wed, 9 Nov 2005 03:41:28 +0900
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
def build_query_string(properties, prop_type)
query = properties.map {|p| "#{p.name}=#{p.value}"}
case prop_type
when "tag": (" " + query.join(" "))
else ("?" + query.join("&"))
end
end
···
--- Ursprüngliche Nachricht ---
Von: marcus <m-lists@bristav.se>
An: ruby-talk@ruby-lang.org (ruby-talk ML)
Betreff: Better way to build string
Datum: Wed, 9 Nov 2005 03:41:28 +0900
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
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
FWIW, I've had a mental block about inject for some time, and this
example very nicely clarified for me what it does and how. Thanks for
the handy example.
Note to OP: Don't forget to use CGI::escape() to properly URL-encode
everything.
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