1
hash = { "d" => [11, 22], "f" => [33, 44, 55] }

is there an one liner to get a string like below:

d:11,d:22,f:33,f:44,f:55

thanks!

Great, thanks for the tip. Why this code doesn't work, only difference is I replaced vs.map with vs.each:

hash.map {|k,vs| vs.each {|v| "#{k}:#{v}"}}.join(",")

which returns "11,22,33,44,55"

2 Answers 2

3

Use two nested calls to map to get an array of arrays of "key:value" strings, and then use join to turn it into one comma-separated string:

hash.map {|k,vs| vs.map {|v| "#{k}:#{v}"}}.join(",")
Sign up to request clarification or add additional context in comments.

2 Comments

why this code doesn't work, only difference is i replaced "vs.map" with "vs.each", hash.map {|k,vs| vs.each {|v| "#{k}:#{v}"}}.join(","), which returns "11,22,33,44,55"
@user: Because each executes the block on each element, but throws the results away and then returns the receiver unchanged. You use each for the side-effects of the block only and in this case there are none. So in other words your code does the same as just hash.map {|k,vs| vs}.join(",").
0
hash.keys.map {|k| hash[k].map {|v| "#{k}:#{v}"}}.flatten.join(",")

1 Comment

Actually you don't need to call flatten before calling join. Join flattens automatically.

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.