【问题标题】:How can i change the output order of a multi-dimensional array in Ruby? [duplicate]如何更改 Ruby 中多维数组的输出顺序? [复制]
【发布时间】:2019-07-08 03:50:30
【问题描述】:

我有这两个数组:

m1 = ["a", "b", "c"]
m2 = ["yes", "no"]

我希望得到以下结果:

expected-output = [["a", "yes"], ["a", "no"],
                   ["b", "yes"], ["b", "no"],
                   ["c", "yes"], ["c", "no"]]

这是我尝试过的代码:

array1 = []
array2 = []
m2.map { |e| m1.map {|i| array1 << i and array2 << e }}
newArray = array1.zip(array2)
print newArray

但我的结果顺序不对:

[["a", "yes"], ["b", "yes"], 
 ["c", "yes"], ["a", "no"], 
 ["b", "no"], ["c", "no"]]

PS:我已经用过sort方法了,还是不行。

【问题讨论】:

  • 只要m1.product(m2)
  • 对于它的价值,你尝试的可以写成m1.flat_map{ |letter| m2.map{ |bool| [letter, bool] } }m1.map { |i| m2.map {|e| array1 &lt;&lt; i; array2 &lt;&lt; e }}。使用product 确实是一个更好的解决方案,但现在您知道如何修复您的代码了。

标签: ruby


【解决方案1】:

为此,您必须使用 Ruby 上可用的 Product 函数。

https://apidock.com/ruby/Array/product

> m1 = ["a", "b", "c"]
=> ["a", "b", "c"]
> m2 = ["yes", "no"]
=> ["yes", "no"]
> m1.product(m2)
=> [["a", "yes"], ["a", "no"], ["b", "yes"], ["b", "no"], ["c", "yes"], ["c", "no"]]

【讨论】:

  • 或许可以用“正如@lurker 建议的那样”作为序言。
  • @CarySwoveland 确实如此,我没有注意到他的回答,抱歉。反正这个问题是Telegram群里的,我之前在那边回复过,就来放这里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2022-11-21
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多