Ruby-on-rails Rails - 使用 %W
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4455429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails - Using %W
提问by AnApprentice
I have the following which works well:
我有以下效果很好:
def steps
%w[hello billing confirmation]
end
steps.first
But I want to do this:
但我想这样做:
def step_title
%w['Upload a photo' 'Billing Info' 'Confirmation Screen']
end
steps.first
How does %w allow for that? I tried a google search but google is weak with these types of characters.
%w 是怎么做到的?我尝试了谷歌搜索,但谷歌对这些类型的字符很弱。
Thanks
谢谢
回答by Brian Rose
%wcreates an "array of words," and uses whitespace to separate each value. Since you want to separate on another value (in this case, whitespace outside sets of quotation marks), just use a standard array:
%w创建一个“单词数组”,并使用空格分隔每个值。由于您想分隔另一个值(在这种情况下,引号外的空格),只需使用标准数组:
['Upload a photo', 'Billing Info', 'Confirmation Screen']
回答by Constantine
%w()is a "word array" - the elements are delimited by spaces.
%w()是一个“字数组” - 元素由空格分隔。
There are other % things:
还有其他 % 的事情:
%r()is another way to write a regular expression.
%r()是另一种编写正则表达式的方法。
%q()is another way to write a single-quoted string (and can be multi-line, which is useful)
%q()是另一种写单引号字符串的方法(并且可以是多行的,这很有用)
%Q()gives a double-quoted string
%Q()给出一个双引号字符串
%x()is a shell command.
%x()是一个shell命令。
回答by iain
You can also use the backslash to escape spaces:
您还可以使用反斜杠来转义空格:
%w@foo\ bar bang@
is the same as:
是相同的:
[ 'foo bar', 'bang' ]
In your example I wouldn't use the %wnotation, because it's not that clear.
在你的例子中,我不会使用这个%w符号,因为它不是那么清楚。
PS. I do like mixing the delimiter characters, just to annoy team members :) Like this:
附注。我确实喜欢混合分隔符,只是为了惹恼团队成员:) 像这样:
%w?foo bar?
%w|foo bar|
%w\foo bar\
%w{foo bar}
回答by yfeldblum
%w[hello billing confirmation]is syntax sugar for ["hello", "billing", "confirmation"]. It tells Ruby to break up the input string into words, based on the whitespace, and to return an array of the words.
%w[hello billing confirmation]是 的语法糖["hello", "billing", "confirmation"]。它告诉 Ruby 根据空格将输入字符串分解为单词,并返回单词数组。
If your specific use case means the values in the array are permitted to have spaces, you cannot use %w.
如果您的特定用例意味着数组中的值允许有空格,则不能使用%w.
In your case, ['Upload a photo', 'Billing Info', 'Confirmation Screen']suffices.
在你的情况下,['Upload a photo', 'Billing Info', 'Confirmation Screen']就足够了。

