将一组任意嵌套的整数数组展平为ruby中的整数平面数组 [英] flatten an array of arbitrarily nested arrays of integers into a flat array of integers in ruby

查看:126
本文介绍了将一组任意嵌套的整数数组展平为ruby中的整数平面数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写代码片段Ruby,它将一组任意嵌套的整数数组展平为一个整数的平面数组。例如[[1,2,[3]],4] - > [1,2,3,4]。请不要使用任何一种语言的任何内置展平函数。

how to write a code snippet Ruby that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. Please don't use any built-in flatten functions in either language.

推荐答案

这是一个不使用内置的解决方案 flatten 方法。它涉及递归

Here's one solution without using the built-in flatten method. It involves recursion

def flattify(array)
  array.each_with_object([]) do |element, flattened|
    flattened.push *(element.is_a?(Array) ? flattify(element) : element)
  end
end

我用irb测试了这个。

I tested this out in irb.

flattify([[1,2,[3],4])
=> [1,2,3,4]

这篇关于将一组任意嵌套的整数数组展平为ruby中的整数平面数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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