Flattening hash into string in Ruby
Posted
by fahadsadah
on Stack Overflow
See other posts from Stack Overflow
or by fahadsadah
Published on 2010-06-15T16:17:35Z
Indexed on
2010/06/15
16:22 UTC
Read the original article
Hit count: 168
Is there a way to flatten a hash into a string, with optional delimiters between keys and values, and key/value pairs?
For example, print {:a => :b, :c => :d}.flatten('=','&')
should print a=b&c=d
I wrote some code to do this, but I was wondering if there was a neater way:
class Hash
def flatten(keyvaldelimiter, entrydelimiter)
string = ""
self.each do
|key, value|
key = "#{entrydelimiter}#{key}" if string != "" #nasty hack
string += "#{key}#{keyvaldelimiter}#{value}"
end
return string
end
end
print {:a => :b, :c => :d}.flatten('=','&') #=> 'c=d&a=b'
Thanks
© Stack Overflow or respective owner