Ruby中的%w {}和%W {}大小写百分比W数组文字有什么区别?

时间:2011-04-22 02:49:54

标签: ruby

%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"]

我的问题是......有什么区别?

3 个答案:

答案 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