%w[ ] Non-interpolated Array of words, separated by whitespace
%W[ ] Interpolated Array of words, separated by whitespace
用法:
p %w{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"]
p %W{one one two three 0 1 1 2 3} # = > ["one", "one", "two", "three", "0", "1", "1", "2", "3"]
p %w{C:\ C:\Windows} # => ["C: C:\\Windows"]
p %W{C:\ C:\Windows} # => ["C: C:Windows"]
我的问题是......有什么区别?
答案 0 :(得分:67)
%W
将字符串视为双引号,而%w
将它们视为单引号(因此不会插入表达式或多个转义序列)。使用ruby表达式再次尝试你的数组,你会发现不同。
实施例
myvar = 'one'
p %w{#{myvar} two three 1 2 3} # => ["\#{myvar}", "two", "three", "1", "2", "3"]
p %W{#{myvar} two three 1 2 3} # => ["one", "two", "three", "1", "2", "3"]
答案 1 :(得分:5)
让我们跳过数组混淆并讨论插值与无:
irb(main):001:0> [ 'foo\nbar', "foo\nbar" ]
=> ["foo\\nbar", "foo\nbar"]
irb(main):002:0> [ 'foo\wbar', "foo\wbar" ]
=> ["foo\\wbar", "foowbar"]
行为上的差异与单引号与双引号字符串的行为方式一致。
答案 2 :(得分:1)
为了演示两种文字都使用内插和序列转义的情况,我们假设:
>> a = 'a'
=> "a"
小写的%w
%文字:
>> %w[a#{a} b#{'b'} c\ d \s \']
=> ["a\#{a}", "b\#{'b'}", "c d", "\\s", "\\'"]
\
大写%W
百分比的文字:
>> %W[a#{a} b#{'b'} c\ d \s \']
=> ["aa", "bb", "c d", " ", "'"]
来源: What is the difference between %w and %W array literals in Ruby