ruby 创建符号数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7354937/
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
Create array of symbols
提问by Drew
Is there a cleaner way to do something like this?
有没有更干净的方法来做这样的事情?
%w[address city state postal country].map(&:to_sym)
#=> [:address, :city, :state, :postal, :country]
I would have figured %swould have done what I wanted, but it doesn't. It just takes everything between the brackets and makes one big symbol out of it.
我本以为%s会做我想做的事,但事实并非如此。它只需要括号之间的所有内容,并从中生成一个大符号。
Just a minor annoyance.
只是一个小烦恼。
回答by Joost Baaij
The original answer was written back in September '11, but, starting from Ruby 2.0, there is a shorter way to create an array of symbols! This literal:
最初的答案是在 11 年 9 月写的,但是,从 Ruby 2.0 开始,有一种更短的方法来创建符号数组!这个字面意思:
%i[address city state postal country]
will do exactly what you want.
会做你想做的。
回答by Joost Baaij
With a risk of becoming too literal, I think the cleanest way to construct an array of symbols is using an array of symbols.
有变得过于文字化的风险,我认为构造符号数组的最简洁方法是使用符号数组。
fields = [:address, :city, :state, :postal, :country]
Can't think of anything more concise than that.
想不出比这更简洁的了。
回答by askrynnikov
%i[ ]Non-interpolated Array of symbols, separated by whitespace (after Ruby 2.0)
%i[ ]非内插符号数组,由空格分隔(Ruby 2.0 之后)
%I[ ]Interpolated Array of symbols, separated by whitespace (after Ruby 2.0)
%I[ ]插入的符号数组,由空格分隔(在 Ruby 2.0 之后)
%i[address city state postal country]
%i[address city state postal country]
the cleanest way to do this is:
最干净的方法是:
%w[address city state postal country].map(&:to_sym)
%w[address city state postal country].map(&:to_sym)

