Ruby on rails 改进使用Ruby';地图';和';splat&x27;

Ruby on rails 改进使用Ruby';地图';和';splat&x27;,ruby-on-rails,ruby,arrays,ruby-on-rails-3,Ruby On Rails,Ruby,Arrays,Ruby On Rails 3,我正在使用RubyonRails 3.2.2,我想改进下面的代码,也许使用一些RubyonRails方法 我有一个数组[“一”、“二”、“三”],我为它创建了一个 # From `Symbol`s to `String`s array = [:one, :two, :three].map {|k| k.to_s} # => ["one", "two", "three"] 然后(下面使用的attr\u accessible方法只是一个示例方法,仅用于说明我的工作;在生产中,我在我的自定义方

我正在使用RubyonRails 3.2.2,我想改进下面的代码,也许使用一些RubyonRails方法

我有一个数组
[“一”、“二”、“三”]
,我为它创建了一个

# From `Symbol`s to `String`s
array = [:one, :two, :three].map {|k| k.to_s}
# => ["one", "two", "three"]
然后(下面使用的
attr\u accessible
方法只是一个示例方法,仅用于说明我的工作;在生产中,我在我的自定义方法中使用“splat”数组)


有没有更好的方法来实现上述目标?如果是这样的话,我如何以“优雅”的方式“转换”数组

array = [:one, :two, :three].map(&:to_s)
使用map_by_方法,您可以执行以下操作:

array = [:one, :two, :three].map_by_to_s
如果您像这样实现自定义方法:

def foo(*args)
  converted_args = args.flatten.map(&:to_s)
end
你可以这样称呼它

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

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

在纯Ruby中,您可以

array = [:one, :two, :three].map(&:to_s)
使用map_by_方法,您可以执行以下操作:

array = [:one, :two, :three].map_by_to_s
如果您像这样实现自定义方法:

def foo(*args)
  converted_args = args.flatten.map(&:to_s)
end
你可以这样称呼它

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

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

你的问题我不清楚。我搞不清楚是要将字符串数组转换为符号数组,还是要将符号数组转换为字符串数组?或者,也许您正在寻找比使用splat更好的解决方案。无论如何

要将字符串转换为符号,请使用To_sym

["one", "two", "three"].map(&:to_sym)
要将符号转换为字符串,请使用To_s(如@Mr.Ronald的答案所示)


你的问题我不清楚。我搞不清楚是要将字符串数组转换为符号数组,还是要将符号数组转换为字符串数组?或者,也许您正在寻找比使用splat更好的解决方案。无论如何

要将字符串转换为符号,请使用To_sym

["one", "two", "three"].map(&:to_sym)
要将符号转换为字符串,请使用To_s(如@Mr.Ronald的答案所示)


你的问题令人困惑。你把符号和字符串搞混了。您的初始代码块是否应该不包含字符串?@Gazler-My first block将数组元素从
Symbol
s转换为
String
s。“您的初始代码块是否应该不包含字符串?”这句话的确切含义是什么?您有一个符号数组,可以将其转换为字符串,但不需要符号?@Gazler-是的,您是对的。然而,
attr\u accessible
只是一个示例方法;我在我的自定义方法中使用了“splat”数组。@Backo,你能更具体地说明你想完成什么吗?你的问题让人困惑。你把符号和字符串搞混了。您的初始代码块是否应该不包含字符串?@Gazler-My first block将数组元素从
Symbol
s转换为
String
s。“您的初始代码块是否应该不包含字符串?”这句话的确切含义是什么?您有一个符号数组,可以将其转换为字符串,但不需要符号?@Gazler-是的,您是对的。然而,
attr\u accessible
只是一个示例方法;我在我的自定义方法中使用了“splat”数组。@Backo,你能更具体地说明你想实现什么吗?