简体   繁体   中英

Flatten an array of strings in Ruby

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(' ') a.map{|dir| "'" + dir + "'"}.join(' ')
eg2: a.reduce("'"){|acc, dir| acc += dir+"' "} 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?

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

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

Try out

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

Or if golfing

?'+a*"' '"+?'

尝试这个:

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

or

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM