Ruby - 分组和投影

时间:2015-02-03 03:24:30

标签: ruby

来自c#,我习惯于使用LINQ

执行以下操作
var people = new List<Person> 
{
    new Person(Race.Black, "Mitch",30),
    new Person(Race.White, "Mike",30),
    new Person(Race.Mexican, "Mel",30),
};

var groups = people.GroupBy (p => p.Race)
                 .Select(g => new {race = g.Key, person = g});

移植到Ruby中,我想将分组和投影分成哈希,但是有没有开箱即用的方法或者我需要自己滚动吗?这是我的实现,但如果用语言提供,或者提供实现的第三方库,它会很棒

def group(arr,group_sym)
  groups = {}
  arr.each do |i|
    race = i[group_sym]
    groups[race] = [] unless groups.has_key?(race)
    i.delete(group_sym)
    groups[race].push(i)
  end

  groups
end

编辑:所以我期待的是以下内容:

输入:

people = [{name: 'mike', race: 'white', age: 30},
{name: 'mel', race: 'white', age: 31},
{name: 'mitch', race: 'black', age: 30},
{name: 'megan', race: 'asian', age: 30},
{name: 'maebe', race: 'black', age: 30},]

函数调用:

groupedPeople = groupBy(people,'race')

返回:

[{'white' => [{name: 'mike', age: 30},
{name: 'mel', race: 'white'}],
{'black' => [{...black people}],
{'asian' => [{...asian people}]


}]

对于这个具体的例子,我想得到一个散列,其中我的people数组按比赛分组

1 个答案:

答案 0 :(得分:1)

由于C#的查询表达式看起来像SQL查询,因此与其他语言相比,方法名称有点不寻常:Select通常称为map,{ {1}}通常称为Aggregatefoldreduce通常称为Whereselect等。

如果只是翻译方法名称,几乎可以将代码翻译成Ruby:

filter

我使用Person = Struct.new(:race, :name, :age) people = [ Person.new(:black, 'Mitch', 30), Person.new(:white, 'Mike', 30), Person.new(:mexican, 'Mel', 30) ] groups = people.group_by(&:race).map {|race, people| { race: race, person: people } } 作为Hash的最接近替代品。