如何在Ruby中有效地串联多个数组? [英] How to efficiently concatenate multiple arrays in Ruby?

查看:99
本文介绍了如何在Ruby中有效地串联多个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在Ruby中连接多个数组,却找不到令人满意的方法.

I just wanted to concatenate multiple arrays in Ruby and couldn't find a satisfying way to do so.

示例输入:

foo = [1, 2, 3]
bar = [4, 5, 6]
baz = [7, 8, 9]

预期结果:(无需修改现有阵列)

Expected result: (without modifying the existing arrays)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

我的实际数组大了 ,所以我对有效的解决方案感兴趣.可能还会有三个以上的数组,因此首选短语法.

My actual arrays are much larger, so I'm interested in an efficient solution. There may also be more than three arrays, so a short syntax is preferred.

  • foo + bar + baz是显而易见的,它简洁明了.但是它被评估为(foo + bar) + baz.换句话说:它创建一个中间数组[1, 2, 3, 4, 5, 6],该中间数组在整个操作后将被丢弃.如文档中所述:

  • foo + bar + baz is the obvious one, it's concise and clear. But it is evaluated as (foo + bar) + baz. In other words: it creates an intermediate array [1, 2, 3, 4, 5, 6] that is thrown away after the whole operation. As noted in the documentation:

在数组上重复使用+=可能效率很低

  • [*foo, *bar, *baz]基本上内联元素,这对于大型数组也不是很有效.在我看来,这更像是一种黑客.

  • [*foo, *bar, *baz] basically inlines the elements which is not very efficient for large arrays, either. It also looks more like a hack to me.

    [foo, bar, baz].flatten(1)似乎比上述情况还要糟糕.

    [foo, bar, baz].flatten(1) seems to be even worse than the above, performance wise.

    [].concat(foo).concat(bar).concat(baz)是最快的,但看起来很麻烦,并且需要多次方法调用.

    [].concat(foo).concat(bar).concat(baz) is the fastest, but it looks cumbersome and it needs multiple method invocations.

    对于这样的基本任务,应该没有简单的类方法吗?像这样:

    Shouldn't there be a simple class method for such a basic task? Something like:

    Array.concat(foo, bar, baz)
    

    我缺少明显的东西吗?

    推荐答案

    如果您已经确定多重连接是最快的方法,则可以使用reduce更好地编写它:

    If you've already determined that multiple concatenation is the fastest method, you can write it nicer using reduce:

    [foo, bar, baz].reduce([], :concat)
    

    这篇关于如何在Ruby中有效地串联多个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆