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

后端 未结 16 846
礼貌的吻别
礼貌的吻别 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条回答
  •  悲&欢浪女
    2020-12-04 05:28

    There are multiple syntaxes for multi-line strings as you've already read. My favorite is Perl-style:

    conn.exec %q{select attr1, attr2, attr3, attr4, attr5, attr6, attr7
          from table1, table2, table3, etc, etc, etc, etc, etc,
          where etc etc etc etc etc etc etc etc etc etc etc etc etc}
    

    The multi-line string starts with %q, followed by a {, [ or (, and then terminated by the corresponding reversed character. %q does not allow interpolation; %Q does so you can write things like this:

    conn.exec %Q{select attr1, attr2, attr3, attr4, attr5, attr6, attr7
          from #{table_names},
          where etc etc etc etc etc etc etc etc etc etc etc etc etc}
    

    I actually have no idea how these kinds of multi-line strings are called so let's just call them Perl multilines.

    Note however that whether you use Perl multilines or heredocs as Mark and Peter have suggested, you'll end up with potentially unnecessary whitespaces. Both in my examples and their examples, the "from" and "where" lines contain leading whitespaces because of their indentation in the code. If this whitespace is not desired then you must use concatenated strings as you are doing now.

提交回复
热议问题