Ruby中的%w {}和%W {}大写和小写的W数组字面量有什么区别?

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

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

%W将string视为双引号,而%w将其视为单引号(因此不会插入expression式或多个转义序列)。 用rubyexpression式再次尝试你的数组,你会看到一个区别。

例:

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

让我们跳过数组混淆,并谈论插值与无:

 irb(main):001:0> [ 'foo\nbar', "foo\nbar" ] => ["foo\\nbar", "foo\nbar"] irb(main):002:0> [ 'foo\wbar', "foo\wbar" ] => ["foo\\wbar", "foowbar"] 

行为上的差异与单引号和双引号string的行为是一致的。

下面是一个例子来回答答案:

 ruby-1.8.7-p334 :033 > @foo = 'bar' => "bar" ruby-1.8.7-p334 :034 > %w(#{@foo}) => ["\#{@foo}"] ruby-1.8.7-p334 :035 > %W(#{@foo}) => ["bar"]