Ruby: Can I write multi-line string with no concatenation?

后端 未结 16 853
礼貌的吻别
礼貌的吻别 2020-12-04 04:42

Is there a way to make this look a little better?

conn.exec \'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \' +
          \'from table1, table2, ta         


        
16条回答
  •  猫巷女王i
    2020-12-04 05:35

    There are pieces to this answer that helped me get what I needed (easy multi-line concatenation WITHOUT extra whitespace), but since none of the actual answers had it, I'm compiling them here:

    str = 'this is a multi-line string'\
      ' using implicit concatenation'\
      ' to prevent spare \n\'s'
    
    => "this is a multi-line string using implicit concatenation to eliminate spare
    \\n's"
    

    As a bonus, here's a version using funny HEREDOC syntax (via this link):

    p <> "SELECT * FROM users ORDER BY users.id DESC"
    

    The latter would mostly be for situations that required more flexibility in the processing. I personally don't like it, it puts the processing in a weird place w.r.t. the string (i.e., in front of it, but using instance methods that usually come afterward), but it's there. Note that if you are indenting the last END_SQL identifier (which is common, since this is probably inside a function or module), you will need to use the hyphenated syntax (that is, p <<-END_SQL instead of p <). Otherwise, the indenting whitespace causes the identifier to be interpreted as a continuation of the string.

    This doesn't save much typing, but it looks nicer than using + signs, to me.

    Also (I say in an edit, several years later), if you're using Ruby 2.3+, the operator <<~ is also available, which removes extra indentation from the final string. You should be able to remove the .gsub invocation, in that case (although it might depend on both the starting indentation and your final needs).

    EDIT: Adding one more:

    p %{
    SELECT * FROM     users
             ORDER BY users.id DESC
    }.gsub(/\s+/, " ").strip
    # >> "SELECT * FROM users ORDER BY users.id DESC"
    

提交回复
热议问题