简体   繁体   English

改进使用Ruby'map'和'splat'转换数组的代码

[英]Improve code that converts an Array using Ruby 'map' and 'splat'

I am using Ruby on Rails 3.2.2 and I would like to improve code below, maybe using some Ruby on Rails method. 我正在使用Ruby on Rails 3.2.2,并且我想在下面改进代码 ,也许使用一些Ruby on Rails方法。

I have an Array ["one", "two", "three"] for which I make 我有一个数组["one", "two", "three"]

# From `Symbol`s to `String`s
array = [:one, :two, :three].map {|k| k.to_s}
# => ["one", "two", "three"]

and then (the attr_accessible method used below is just a sample method and only serves to give an idea of what I do; in production I use the "splat" array in a my custom method) 然后(下面使用的attr_accessible方法只是一个示例方法,仅用于提供我的想法;在生产中,我在自定义方法中使用“ splat”数组)

attr_accessible *array
# => attr_accessible "one", "two", "three"

Is there a better way to make the above? 有没有更好的方法可以做到以上几点? If so, how can I "convert" the ["one", "two", "three"] array in an "elegant" way? 如果是这样,如何以一种“优雅”的方式“转换” ["one", "two", "three"]数组?

In plain Ruby you can do 在普通的Ruby中,您可以做

array = [:one, :two, :three].map(&:to_s)

With the map_by_method gem you can do: 使用map_by_method gem,您可以执行以下操作:

array = [:one, :two, :three].map_by_to_s

If you implement your custom method like this: 如果您像这样实现自定义方法:

def foo(*args)
  converted_args = args.flatten.map(&:to_s)
end

You can call it like 你可以这样称呼它

 foo "one", "two", "three"
 foo :one, :two, :three

 args = [:one, :two, :three]
 foo *args
 foo args # see flatten above

Your question is unclear to me. 我不清楚您的问题。 I can't make out whether you want to convert an array of strings to an array of symbols, or if you want to convert an array of symbols to an array of strings? 我无法确定是要将字符串数组转换为符号数组,还是要将符号数组转换为字符串数组? Or maybe you're looking for a better solution than using splat. 或者,也许您正在寻找比使用splat更好的解决方案。 In any case ... 任何状况之下 ...

To convert strings to symbols, use to_sym. 要将字符串转换为符号,请使用to_sym。

["one", "two", "three"].map(&:to_sym)

To convert symbols to strings, use to_s (as @Mr.Ronald's answer shows) 要将符号转换为字符串,请使用to_s(如@ Mr.Ronald的答案所示)

[:one, :two, :three].map(&:to_s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM