简体   繁体   中英

Ruby: Concise way to conditionally join strings with newlines?

I need to add a description string to an existing comments variable, which contains either a string or nil . I want to separate the new description from any existing comments with a newline, but only if there are existing comments. I've come up with a couple ways that are kind of concise,

old_comments = comments + "\n" rescue ""
new_comments = old_comments + description

or

new_comments = [comments, description].compact.join("\n")

but I'm surprised there's not a less "tricky" way to squeeze this into a one-liner. Or is there?

[*comments, description].join($/)

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