如何与QUOT; unflatten"一个Ruby数组? [英] How to "unflatten" a Ruby Array?

查看:118
本文介绍了如何与QUOT; unflatten"一个Ruby数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在这个红宝石数组转换:

I am currently trying to convert this ruby array:

[5, 7, 8, 1]

这个:

[[5], [7], [8], [1]]

什么是最好的方法是什么?

What's the best way ?

目前,我正在做这样的:

I'm currently doing it like this:

[5, 7, 8, 1].select { |element| element }.collect { |element| element.to_a }

但我发现了以下错误(S):

But I'm getting the following error(s):

警告:默认的`to_a将过时

我是什么做错了吗?
能否请您就如何做到这一点正确的建议?

What am I doing wrong? Could you please advice on how to do this right?

在此先感谢和最诚挚的问候!

Thanks in advance and best regards!

推荐答案

最短,最快的解决方案是使用的 阵列#拉链

The shortest and fastest solution is using Array#zip:

values = [5, 7, 8, 1]
values.zip # => [[5], [7], [8], [1]]

另一种可爱的方式是使用

[values].transpose # =>  [[5], [7], [8], [1]]

最直观的方法可能就是@Thom提示:

The most intuitive way is probably what @Thom suggests:

values.map{|e| [e] }

这篇关于如何与QUOT; unflatten"一个Ruby数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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