我如何将一个函数应用到数组并形成两个单独的数组? [英] How do I apply a function to an array and form two separate arrays?

查看:121
本文介绍了我如何将一个函数应用到数组并形成两个单独的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ruby 2.4。我有一个字符串数据元素的数组,看起来像

I'm using Ruby 2.4. I have an array with string data elements, that look like

["a word1 word2", "b eff", "a idaho orange", "new old shoe", "b mars", ...]

我想从上面形成两个数组,将一个函数( .split(/ ^(a | b)[[:space]] * / i )应用于然而,我不知道如何形成两个单独的数组。下面的

I want to form two arrays from the above, applying a function (.split(/^(a|b)[[:space]]*/i) to each element of the array. However, I can't figure out how to form two separate arrays. The following

arr.map{ |x| x.split(/^(a|b)[[:space]]*/i) }

只会产生一个数组,并且在每个元素的前面都有一个空元素。理想情况下,我希望输出是两个数组,如

only results in a single array and has a blank element in front of each element. Ideally, I'd like the output to be two arrays like

["a", "b", "a", "", "b", ...]
["word1 word2", "eff", "idaho orange", "new old shoe", "mars", ...]


推荐答案

试试这个

arr.map { |x| a, b, c = x.partition(/^[ab]\s+/); [b.strip, a + c] }.transpose

这是如何工作的?


  • 分区将字符串拆分为before-match,match和后续匹配

  • b.strip 是没有尾随空白的匹配

  • a + c 是完整字符串(如果没有匹配,则完整字符串在匹配前)或后期匹配

  • [...,...] 创建一个元组,因此创建一个元组数组

  • 转置切换2D数组的行和列

  • partition splits a string into before-match, match and post-match
  • b.strip is the match without trailing whitespace
  • a + c is either the full string (if there was no match the full string is in before-match) or the post-match
  • [..., ...] creates a tuple, hence creating an array of tuple
  • transpose switches the rows and columns of a 2D array

这篇关于我如何将一个函数应用到数组并形成两个单独的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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