ruby 字符串分隔符中“%{}"、“%Q{}"、“%q{}"之间的区别 [英] Difference between '%{}', '%Q{}', '%q{}' in ruby string delimiters

查看:45
本文介绍了ruby 字符串分隔符中“%{}"、“%Q{}"、“%q{}"之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于 ruby​​ 的在线教程,发现了这个通用分隔字符串",

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{a word} # equivalent to single quoted version.

所以我在 irb 上试了一下,这就是我所看到的

so i tried it on irb and this is what i see

2.0.0p247 :025 > %Q(hi)
 => "hi" 
2.0.0p247 :026 > %q(the)
 => "the" 
2.0.0p247 :027 > %q(th"e)
 => "th\"e" 
2.0.0p247 :028 > %q(th'e)
 => "th'e" 
2.0.0p247 :029 > %Q(h'i)
 => "h'i" 
2.0.0p247 :030 > %Q(h"i)
 => "h\"i"

%q 和 %Q 的行为相同,并使用双引号中的字符串.如果我们可以使用 %{} 来获得相同的输出,那么任何人都知道这两个的确切用途是什么.

Both %q and %Q behave the same and takes string in double quotes. Anybody know what exactly the use of these 2 if we can use %{} to get the same output.

推荐答案

这里有一些关于它们的提示 Ruby_Programming - % 符号:

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

%Q[ ] - 内插字符串(默认)

%Q[ ] - Interpolated String (default)

%q[ ] - 非内插字符串(除了 \ 、 [ 和 ])

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

示例:

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.

这篇关于ruby 字符串分隔符中“%{}"、“%Q{}"、“%q{}"之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆