为什么我会使用非插值字符串?
当然你不想插值。例如,也许您输出一些文件有关的字符串插值:
'Use #{x} to interpolate the value of x.'
=> "Use #{x} to interpolate the value of x."
请问%语法有什么优势引述文字?
它可以让你写串更自然,不带引号,或当你不想逃避很多东西,类似于C#的字符串文字前缀@
。
%{The % syntax make strings look more "natural".}
=> "The % syntax makes strings look more \"natural\"."
%{<basket size="50">}
=> "<basket size=\"50\">"
还有许多其他%-notations:
%w{apple banana #{1}cucumber} # [w]hitespace-separated array, no interpolation
=> ["apple", "banana", "\#{1}cucumber"]
%W{apple banana #{1}cucumber} # [W]hitespace-separated array with interpolation
=> ["apple", "banana", "1cucumber"]
# [r]egular expression (finds all unary primes)
%r{^1?$|^(11+?)\1+$}
=> /^1?$|^(11+?)\1+$/
(1..30).to_a.select{ |i| ("1" * i) !~ %r{^1?$|^(11+?)\1+$} }
=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
%x{ruby --version} # [s]hell command
=> "ruby 1.9.1p129 (2009-05-12 revision 23412) [x86_64-linux]\n"
还有%s
(用于符号)和其他一些人。
为什么有五种方法来创建字符串文字?
这不是非常不寻常的。例如,考虑C#,它有几种不同的方式来生成字符串:new String()
; ""
; @""
; StringBuilder.ToString()
等等。
“自然”是非常主观的。 “非常不寻常”不是创建语言功能的动机。 – skrat 2012-02-07 16:46:10
“自然”具有很高的主观性,但“更少且更容易输入字符来表示完全相同的东西”不是,而且是创建语言功能的一个很好的动机。 – 2012-02-07 18:34:19