在Ruby中,%w{}和%w{}上下大小写百分比w阵列字元之间的区别是什么?

时间:2022-01-16 13:06:02
%w[ ]   Non-interpolated Array of words, separated by whitespace
%W[ ]   Interpolated Array of words, separated by whitespace

Usage:

用法:

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

My question is... what's the difference?

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

3 个解决方案

#1


60  

%W treats the strings as double quoted whereas %w treats them as single quoted (and therefore won’t interpolate expressions or numerous escape sequences). Try your arrays again with ruby expressions and you'll see a difference.

%W将字符串视为双引号,而%W将它们视为单引号(因此不会插入表达式或大量转义序列)。再次使用ruby表达式尝试数组,您将看到不同之处。

EXAMPLE:

例子:

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

#2


5  

Let's skip the array confusion and talk about interpolation versus none:

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

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

The difference in behavior is consistent with how single-quoted versus double-quoted strings behave.

行为上的差异与单引号字符串和双引号字符串的行为一致。

#3


2  

Here's an example to acconrads answer:

这里有一个例子来说明答案:

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

#1


60  

%W treats the strings as double quoted whereas %w treats them as single quoted (and therefore won’t interpolate expressions or numerous escape sequences). Try your arrays again with ruby expressions and you'll see a difference.

%W将字符串视为双引号,而%W将它们视为单引号(因此不会插入表达式或大量转义序列)。再次使用ruby表达式尝试数组,您将看到不同之处。

EXAMPLE:

例子:

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

#2


5  

Let's skip the array confusion and talk about interpolation versus none:

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

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

The difference in behavior is consistent with how single-quoted versus double-quoted strings behave.

行为上的差异与单引号字符串和双引号字符串的行为一致。

#3


2  

Here's an example to acconrads answer:

这里有一个例子来说明答案:

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