【问题标题】:Improve code that converts an Array using Ruby 'map' and 'splat'改进使用 Ruby 'map' 和 'splat' 转换数组的代码
【发布时间】:2012-05-11 22:29:17
【问题描述】:

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

我有一个数组 ["one", "two", "three"] 用于制作

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

然后(下面使用的attr_accessible 方法只是一个示例 方法,仅用于说明我的工作;在生产中,我在自定义中使用“splat”数组方法)

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

有没有更好的方法来制作上述内容?如果是这样,我怎样才能以“优雅”的方式“转换”["one", "two", "three"] 数组?

【问题讨论】:

  • 您的问题令人困惑。您将符号和字符串混合在一起。您的初始代码块应该不包含字符串吗?
  • @Gazler - 我的第一个块将数组元素从 Symbols 转换为 Strings。 “您的初始代码块应该不包含字符串吗?”到底是什么意思?
  • 您有一个符号数组,您可以将其转换为字符串,但 attr_accessible 不期望符号?
  • @Gazler - 是的,你是对的。但是,attr_accessible 只是一个示例方法;我在自定义方法中使用“splat”数组。
  • @Backo,您能否更具体地说明您要完成的工作?

标签: ruby-on-rails ruby arrays ruby-on-rails-3


【解决方案1】:

在普通的 Ruby 中你可以做到

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

使用 map_by_method gem,您可以:

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

【讨论】:

    【解决方案2】:

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

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

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

    要将符号转换为字符串,请使用 to_s(如@Mr.Ronald 的回答所示)

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

    【讨论】:

      猜你喜欢
      • 2010-10-29
      • 2012-09-22
      • 2023-03-16
      • 2023-01-18
      • 1970-01-01
      • 2015-02-23
      • 2013-07-04
      • 2017-01-09
      • 2012-09-20
      相关资源
      最近更新 更多