拆分阵列成红宝石多个小数组的最佳方法 [英] Best way to split arrays into multiple small arrays in ruby

查看:88
本文介绍了拆分阵列成红宝石多个小数组的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是阵列分成基于某些条件下多个阵列最简单的方法?在我的方案,我需要移动整数,字符串值不同的阵列。我曾尝试拆分方法,但并不如预期正常工作。

What is the simplest way to split arrays into multiple arrays based on some conditions? In my scenario, I need to move the integer and the string values to different arrays. I have tried split method, but does not work as expected.

x=[1,2,3,"a","b",4]
x.split {|item| item.kind_of? Fixnum}

在C#中,有一个选项的LINQ 的基础上,它可以帮助您组对象条件。是否有关于对象(不使用ActiveRecord)?

In C#, there is a group by option in Linq, which helps you group the objects based on the conditions. Is there a similar method on Object (not using activerecord) ?

有一个简单的方法是什么?

Is there a simple way?

推荐答案

您正在寻找的Enumerable#partition:

x = [1, 2, 3, "a", "b", 4]
numbers, not_numbers = x.partition{|item| item.kind_of?(Fixnum)}
# => [[1, 2, 3, 4], ["a", "b"]]

这篇关于拆分阵列成红宝石多个小数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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