【问题标题】:How to substitute all the values in a two-dimensional array in Ruby如何在Ruby中替换二维数组中的所有值
【发布时间】:2014-02-08 15:59:48
【问题描述】:

我有一个如下所示的二维数组:

[true,false,false]
[false,true,false]
[false,false,true]

我希望我可以将所有 true(bool) 值替换为 'true'(string) 并将所有 false 替换为 '假'

【问题讨论】:

    标签: ruby arrays map string-substitution


    【解决方案1】:

    是的,使用Array#map

    a = [[true,false,false], [false,true,false], [false,false,true]]
    # you can also assign this to a new local variable instead of a,
    # if you need to use your source array object in future anywhere.
    a = a.map { |e| e.map(&:to_s) } 
    

    【讨论】:

      【解决方案2】:

      假设你有一个数组数组:

      a = [[true,false,false], [false,true,false], [false,false,true]]
      a.each { |x| x.map!(&:to_s) }
      a # => [["true", "false", "false"], ["false", "true", "false"], ["false", "false", "true"]]
      

      【讨论】:

      • 不是线程安全的。 Arup 两次使用 map 的答案更好。投票取消删除他的...
      • @Denis 线程安全不是 OP 中的要求。 MRI 中的Array 也不是线程安全的。
      • @Denis 实际上您无法知道最佳答案,因为您不知道确切要求。您假设线程安全在这里是一个问题,尽管 OP 对此只字未提。
      • 我只是指出一个答案会留下一个悬空的、难以追踪的错误,如果它曾经在线程中使用,它会在你的脸上炸开,而另一个答案不会。从这个角度来看,后者简直比前者好。
      • @Denis 另一方面,就性能而言,这比其他答案要好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      相关资源
      最近更新 更多