Which style of Ruby string quoting do you favour?

后端 未结 9 1768
挽巷
挽巷 2020-11-30 00:31

Which style of Ruby string quoting do you favour? Up until now I\'ve always used \'single quotes\' unless the string contains certain escape sequences or interp

相关标签:
9条回答
  • 2020-11-30 01:10

    Single quote preserve the characters inside them. But double quotes evaluate and parse them. See the following example:

    "Welcome #{@user.name} to App!" 
    

    Results:

    Welcome Bhojendra to App!

    But,

    'Welcome #{@user.name} to App!'
    

    Results:

    Welcome #{@user.name} to App!

    0 讨论(0)
  • 2020-11-30 01:11

    I always use single quotes unless I need interpolation.

    Why? It looks nicer. When you have a ton of stuff on the screen, lots of single quotes give you less "visual clutter" than lots of double quotes.

    I'd like to note that this isn't something I deliberately decided to do, just something that I've 'evolved' over time in trying to achieve nicer looking code.

    Occasionally I'll use %q or %Q if I need in-line quotes. I've only ever used heredocs maybe once or twice.

    0 讨论(0)
  • 2020-11-30 01:11

    Like many programmers, I try to be as specific as is practical. This means that I try to make the compiler do as little work as possible by having my code as simple as possible. So for strings, I use the simplest method that suffices for my needs for that string.

    <<END
    For strings containing multiple newlines, 
    particularly when the string is going to
    be output to the screen (and thus formatting
    matters), I use heredocs.
    END
    
    %q[Because I strongly dislike backslash quoting when unnecessary, I use %Q or %q
    for strings containing ' or " characters (usually with square braces, because they
    happen to be the easiest to type and least likely to appear in the text inside).]
    
    "For strings needing interpretation, I use %s."%['double quotes']
    
    'For the most common case, needing none of the above, I use single quotes.'
    

    My first simple test of the quality of syntax highlighting provided by a program is to see how well it handles all methods of quoting.

    0 讨论(0)
提交回复
热议问题