创建符号数组 [英] Create array of symbols

查看:52
本文介绍了创建符号数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更简洁的方法来做这样的事情?

Is there a cleaner way to do something like this?

%w[address city state postal country].map(&:to_sym) 
#=> [:address, :city, :state, :postal, :country]

我本以为 %s 会做我想做的事,但事实并非如此.它只需要括号之间的所有内容,并从中生成一个大符号.

I would have figured %s would have done what I wanted, but it doesn't. It just takes everything between the brackets and makes one big symbol out of it.

只是一个小小的烦恼.

推荐答案

原始答案写于 11 年 9 月,但是,从 Ruby 2.0 开始,有一种更短的方法来创建符号数组!这个文字:

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:

%i[address city state postal country]

会做你想做的事.

这篇关于创建符号数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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