AnA*_*ice 39 ruby-on-rails ruby-on-rails-3
我有以下哪个效果很好:
def steps
%w[hello billing confirmation]
end
steps.first
Run Code Online (Sandbox Code Playgroud)
但我想这样做:
def step_title
%w['Upload a photo' 'Billing Info' 'Confirmation Screen']
end
steps.first
Run Code Online (Sandbox Code Playgroud)
%w如何允许?我试过谷歌搜索,但谷歌这些类型的字符很弱.
谢谢
小智 56
%w创建一个"单词数组",并使用空格来分隔每个值.由于您要分隔另一个值(在本例中为引号外的空格),只需使用标准数组:
['Upload a photo', 'Billing Info', 'Confirmation Screen']
Run Code Online (Sandbox Code Playgroud)
小智 34
%w() 是一个"字数组" - 元素由空格分隔.
还有其他的东西:
%r() 是编写正则表达式的另一种方法.
%q() 是另一种编写单引号字符串的方法(可以是多行的,这很有用)
%Q() 给出一个双引号字符串
%x() 是一个shell命令.
iai*_*ain 10
您还可以使用反斜杠来转义空格:
%w@foo\ bar bang@
Run Code Online (Sandbox Code Playgroud)
是相同的:
[ 'foo bar', 'bang' ]
Run Code Online (Sandbox Code Playgroud)
在你的例子中,我不会使用%w符号,因为它不是那么清楚.
PS.我喜欢混合分隔符,只是为了惹恼团队成员:)像这样:
%w?foo bar?
%w|foo bar|
%w\foo bar\
%w{foo bar}
Run Code Online (Sandbox Code Playgroud)
%w[hello billing confirmation]是 的语法糖["hello", "billing", "confirmation"]。它告诉 Ruby 根据空格将输入字符串分解为单词,并返回单词数组。
如果您的特定用例意味着数组中的值允许有空格,则不能使用%w.
在你的情况下,['Upload a photo', 'Billing Info', 'Confirmation Screen']就足够了。
| 归档时间: |
|
| 查看次数: |
29589 次 |
| 最近记录: |