当使用%重量? [英] When to use %w?

查看:141
本文介绍了当使用%重量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的两个语句会产生相同的结果:

The following two statements will generate the same result:

arr = %w(abc def ghi jkl)

arr = ["abc", "def", "ghi", "jkl"]

在哪些情况下应%重量使用吗?

In which cases should %w be used?

在上面的例子中,我想一个数组 [ABC,高清,GHI,京客隆] 。这是理想的方式:前者(与%重量)或更高版本

In the case above, I want an array ["abc", "def", "ghi", "jkl"]. Which is the ideal way: the former (with %w) or the later?

推荐答案

在使用%W [...] 与一个普通阵列?我相信你能想起来的原因仅仅通过看两下,然后键入方式,并思考自己刚才做了。

When to use %w[...] vs. a regular array? I'm sure you can think up reasons simply by looking at the two, and then typing them in, and thinking about what you just did.

使用%W [...] 当你有你要变成一个数组单个单词的列表。我用它时,我有我的参数要循环结束,或命令我知道我会想在将来添加到,因为%W [...] 使得很容易地新的元素添加到阵列中。有一个在数组的定义不太视觉噪声。

Use %w[...] when you have a list of single words you want to turn into an array. I use it when I have parameters I want to loop over, or commands I know I'll want to add to in the future, because %w[...] makes it easy to add new elements to the array. There's less visual noise in the definition of the array.

当你有嵌入了空格,将诱骗%重量元素使用的字符串规则排列。使用它对于必须包含不是字符串数组的元素。围内的元素 与干预逗号引起视觉噪声,但也使得它可以创建数组与任何对象类型。

Use a regular array of strings when you have elements that have embedded white-space that would trick %w. Use it for arrays that have to contain elements that are not strings. Enclosing the elements inside " and ' with intervening commas causes visual-noise, but it also makes it possible to create arrays with any object type.

所以,你选择何时使用一个或另一个时,它是很有道理的给你。这就是所谓的程序员的选择。

So, you pick when to use one or the other when it makes the most sense to you. It's called "programmer's choice".

这篇关于当使用%重量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆