爲什麼我會使用非插值字符串?
當然你不想插值。例如,也許您輸出一些文件有關的字符串插值:
'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