的Ruby / Rails组只能在相邻的数组元素 [英] Ruby / Rails Groups only Adjacent Array Elements

查看:163
本文介绍了的Ruby / Rails组只能在相邻的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个排序的数组全面的对象,我想这组由一个属性,但只有当他们的阵列中的相邻。

A 被排序的启动属性。

A = [{名:乔,启动:上午9点,结束:上午10时},
    {名:乔,启动:上午10时,结束:上午11时},
    {名:哈里,启动:11点,结束:12点},
    {名:哈里,启动:12点,结束:下午1点},
    {名:哈里,开始下午1点,结束:下午},
    {名:乔,启动:下午2点,结尾:「下午3},
    {名:乔,启动15:00,结束:下午4点}]

我想由名称属性组相邻的对象,这样的结果是这样的:

  A = [[{名:乔,启动:上午9点,结束:上午10时},{名字:乔,启动:上午10点,结束上午11时}],
    [{名:哈里,启动:11点,结束:12点},{名字:哈里,启动:12点,结束:下午1点},{名字:哈里,启动: 下午1点,结束:下午2}],
    [{名:乔,开始下午,结束:下午3点},{名字:乔,启动15:00,结束:下午4点}]


解决方案

这应该做的:

  a.chunk {|哈希|哈希[:名字]}的地图。(安培;:上)

I have a sorted array full of objects which I'd like to group by an attribute, but only if they're adjacent in the array.

a is sorted by the start attribute.

a = [{name: "joe", start: "9am", end: "10am"}, {name: "joe", start: "10am", end: "11am"}, {name: "harry", start: "11am", end: "12pm"}, {name: "harry", start: "12pm", end: "1pm"}, {name: "harry", start: "1pm", end: "2pm"}, {name: "joe", start: "2pm", end: "3pm"}, {name: "joe", start: "3pm", end: "4pm"}]

I would like to group adjacent objects by the name attribute so the results looks like:

a = [[{name: "joe", start: "9am", end: "10am"},{name: "joe", start: "10am", end: "11am"}],
    [{name: "harry", start: "11am", end: "12pm"},{name: "harry", start: "12pm", end: "1pm"},{name: "harry", start: "1pm", end: "2pm"}],
    [{name: "joe", start: "2pm", end: "3pm"},{name: "joe", start: "3pm", end: "4pm"}]]

解决方案

This should do:

a.chunk {|hash| hash[:name]}.map(&:last)

这篇关于的Ruby / Rails组只能在相邻的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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