15

What's the best idiomatic (cleanest) way to convert an array of strings into a string, while keeping the enclosing quotes for each elements.
In other words, from this:

a = ["file 1.txt", "file 2.txt", "file 3.txt"]

I'd need to get this

"'file 1.txt' 'file 2.txt' 'file 3.txt'"

Single and double quotes could be interchanged here. The best ways I know of is by using map and inject/reduce.

eg: a.map{|dir| "'" + dir + "'"}.join(' ')
eg2: a.reduce("'"){|acc, dir| acc += dir+"' "}

Performance could be improved by avoiding temp string creation (+ operator). That's not my main question though. Is there a cleaner more concise way to achieve the same result?

2
  • Do you need to escape quotes inside array members? Commented Aug 19, 2010 at 16:15
  • No, only to keep the beginning and end quotes as shown above for the array. I realise that the quotes shown are not in the strings themselves and that's why they are stripped when doing only a join on the array.
    – Bernard
    Commented Aug 19, 2010 at 23:04

4 Answers 4

29

Shorter doesn't always mean simpler. Your first example was succinct, readable, and easily changeable, without being unnecessarily complex.

a.map { |s| "'#{s}'" }.join(' ')
14

Try out

"'#{a.join("' '")}'"

Or if golfing

?'+a*"' '"+?'
3
  • 1
    All those quotes are finicky but you've got the best answer so far.
    – Bernard
    Commented Aug 20, 2010 at 3:25
  • 3
    I'm not saying this is bad, but it doesn't exactly read naturally either. It's the sort of thing that will make even an experienced Rubyist go "Huh?" at first glance.
    – Chuck
    Commented Aug 20, 2010 at 4:33
  • Interesting golf putt! Commented Nov 11, 2016 at 1:13
1

Try this:

"'" + a.join("' '") + "'"
0
"'"+a*"' '"+"'"

or

"'#{a*"' '"}'"

or

a.to_s[1...-1].gsub /",?/,"'"

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.