Examples of the use of percent and literal characters in Ruby _ruby topics

Source: Internet
Author: User

A single line string that needs to be interpolated and embedded with double quotes uses% () (abbreviated as%Q). Multi-line string, preferably with Heredocs.

  # bad (no interpolation needed)
  % (<div class= "text" >some text</div>)
  # should to be ' <div class= ' Text ' >some text</div> '

  # Bad (no double-quotes)
  % (the This is #{quality} style)
  # should be ' this is #{qu Ality} style "

  # bad (multiple lines)
  % (<div>\n<span class= ' big ' >#{exclamation}</span>\n </div>)
  # should be a heredoc.

  # Good (requires interpolation, has quotes, single line)
  % (<tr><td class= "name" >#{name}</td>)

No ' and ' strings do not use%q. Normal strings are more readable unless many characters need to be escaped.

  # bad
  name =%q (Bruce Wayne) Time
  =%q (8 o ' clock)
  question =%q ("What did for you say?")

  # good
  name = ' Bruce Wayne ' time
  = ' 8 o ' clock '
  question = ' What did you say? '

The%r method is only suitable for defining regular expressions that contain multiple/symbols.

  # bad
  %r (\s+)

  # still-
  %r (^/(. *) $)
  # should be/^\/(. *) $/

  # good
  %r (^/blog/2011/(. *) $)

Do not use%x unless you have used an inverted quotation mark in the command you invoked (this is uncommon).

  # bad
  date =%x (date)

  # good
  date = ' Date '
  echo =%x (echo ' Date ')

Do not use%s. Communities tend to use: "Some string" to create symbols that contain whitespace.

Use () with% literal, except for%r. Because curly braces often appear in regular expressions in many scenes, characters that are less common in many scenes, such as {as delimiters, may be a better choice, depending on the contents of the regular formula.

  # bad
  %w[one two three]
  %q{"Test ' king!", John said.}

  # good
  %w (one Two three)
  %q ("Test ' king!", John said.)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.