Difference between '%{}', '%Q{}', '%q{}' in ruby string delimiters

后端 未结 2 1119
心在旅途
心在旅途 2020-12-15 03:44

I was going through an online tutorial on ruby and found this \"General Delimited Strings\",

%{a word}  # => \"a word\"
%Q{a word} # => \"a word\"
%q{         


        
相关标签:
2条回答
  • 2020-12-15 04:23

    %q(no interpolation)

    %Q(interpolation and backslashes)

    %(interpolation and backslashes)

    Example

    $ str = 'sushant'
    
    $ %q[#{str} "mane"]
     => "\#{str} \"mane\""
    
    $ %Q[#{str} "mane"]
     => "sushant \"mane\""
    
    $ %[#{str} "mane"]
     => "sushant \"mane\""
    
    0 讨论(0)
  • 2020-12-15 04:31

    Here is some hints about them Ruby_Programming - The % Notation:

    %Q[ ] - Interpolated String (default)

    %q[ ] - Non-interpolated String (except for \ , [ and ])

    Example :

    x = "hi"
    p %Q[#{x} Ram!] #= > "hi Ram!"
    p %q[#{x} Ram!] #= > "\#{x} Ram!"
    p %Q[th\e] #= > "th\e"
    p %q[th\e] #= > "th\\e" # notice the \\ with %q[]
    

    Another good resource Percent Strings

    Besides %(...) which creates a String, The % may create other types of object. As with strings, an uppercase letter allows interpolation and escaped characters while a lowercase letter disables them.

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