Which style of Ruby string quoting do you favour?

后端 未结 9 1767
挽巷
挽巷 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 00:56

    Don't use double quotes if you have to escape them. And don't fall in "single vs double quotes" trap. Ruby has excellent support for arbitrary delimiters for string literals:

    Mirror of Site - https://web.archive.org/web/20160310224440/http://rors.org/2008/10/26/dont-escape-in-strings

    Original Site - http://rors.org/2008/10/26/dont-escape-in-strings

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

    I use single quotes unless I need interpolation, or the string contains single quotes.

    However, I just learned the arbitrary delimiter trick from Dejan's answer, and I think it's great. =)

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

    I see arguments for both:

    For using mostly double quotes:

    • The github ruby style guideline advocates always using double quotes:

    enter image description here

    • It's easier to search for a string foobar by searching for "foobar" if you were consistent with quoting. However, I'm not. So I search for ['"]foobar['"] turning on regexps.

    For using some combination of single double quotes:

    • Know if you need to look for string interpolation.
    • Might be slightly faster (although so slight it wasn't enough to affect the github style guide).
    0 讨论(0)
  • 2020-11-30 01:06

    I usually use double quotes unless I specifically need to disable escaping/interpolation.

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

    I use single quotes unless I need interpolation. The argument about it being troublesome to change later when you need interpolation swings in the other direction, too: You have to change from double to single when you found that there was a # or a \ in your string that caused an escape you didn't intend.

    The advantage of defaulting to single quotes is that, in a codebase which adopts this convention, the quote type acts as a visual cue as to whether to expect interpolated expressions or not. This is even more pronounced when your editor or IDE highlights the two string types differently.

    I use %{.....} syntax for multi-line strings.

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

    I used to use single quotes until I knew I needed interpolation. Then I found that I was wasting a lot of time when I'd go back and have to change some single-quotes to double-quotes. Performance testing showed no measurable speed impact of using double-quotes, so I advocate always using double-quotes.

    The only exception is when using sub/gsub with back-references in the replacement string. Then you should use single quotes, since it's simpler.

    mystring.gsub( /(fo+)bar/, '\1baz' )
    mystring.gsub( /(fo+)bar/, "\\1baz" )
    0 讨论(0)
提交回复
热议问题