3

there is a Hash like this:

params = { k1: :v1, k2: :v2, etc: :etc }

i need it converted to a string like this:

k1="v1", k2="v2", etc="etc"

i have a working version:

str = ""
params.each_pair { |k,v| str << "#{k}=\"#{v}\", " }

but it smells like ten PHP spirits ...

what's the Ruby way to do this?

2
  • Every object has to_s method in ruby. Commented Nov 1, 2012 at 7:05
  • yep, i know, but the output is quite different from what i need Commented Nov 1, 2012 at 7:11

2 Answers 2

4

try this:

str = params.map {|p| '%s="%s"' % p }.join(', ')

see it in action here

Sign up to request clarification or add additional context in comments.

4 Comments

splendid, how does it work? i feel my mind is seriously screwed by long PHP years... :( Djkastra was right - some languages does seriously damaging human minds
@oldergod, sorry? you simply call params.map in your code and it should work
@JamesEvans, you asking how does it work? simply. map block receives an array of key/val as first arg and we feed it to %, which is a shorthand for printf
I did not know it was a shorthand for printf and that is what I was asking for. Thanks, great answer.
1

Try this...

hash.collect { |k,v| "#{k} = #{v}" }.join(" ,")

3 Comments

much better but i need value in double quotes
try this...hash.collect { |k,v| "#{k} = '#{v}' " }.join(" ,")...the compiler throws up backslashes when we try to change the order of double and single quotes...
hash.collect { |k,v| "#{k} = \"#{v}\"" }.join(" ,")...this is also an option but the o/p is "k1 = \"v1\" ,k2 = \"v2\" ,etc = \"etc\""

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.