ruby数组/列表的多类分区函数

时间:2017-01-04 16:30:50

标签: ruby dictionary filter functional-programming reduce

我刚刚深入研究了ruby的功能方面,并且正在摆弄map / reduce和一些过滤。

我现在已经达到了以下结构列表:

{:price=>100.0, :size=>'small', :description=>'some description'} 

:size的值可能是['small', 'medium', 'large']之一。

有没有办法将整个列表划分为子列表,只包含那些大小,中,大的元素而不为每个值设置过滤函数?

基本上我要问的是有一些多类Array.partition。

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

我相信您正在寻找Enumberable#group_by

list = [
  {:price=>100.0, :size=>'small', :description=>'some description'},
  {:price=>123.0, :size=>'small', :description=>'some description 2'},
  {:price=>456.0, :size=>'medium', :description=>'some description 3'}
]

list.group_by {|item| item[:size]}
  # => {
  #      "small" => [
  #        {:price=>100.0, :size=>"small", :description=>"some description"},
  #        {:price=>123.0, :size=>"small", :description=>"some description 2"}
  #      ],
  #      "medium" => [
  #        {:price=>456.0, :size=>"medium", :description=>"some description 3"}
  #      ]
  #    }

答案 1 :(得分:3)

input = [
  {:price=>100.0, :size=>'small', :description=>'some description 1'},
  {:price=>100.0, :size=>'large', :description=>'some description 2'},
  {:price=>100.0, :size=>'small', :description=>'some description 3'},
  {:price=>100.0, :size=>'large', :description=>'some description 4'},
  {:price=>100.0, :size=>'small', :description=>'some description 5'},
  {:price=>100.0, :size=>'small', :description=>'some description 6'}
]

input.group_by { |e| e[:size] }

您是否认为结果不应包含哈希值,请使用Hash#delete来改变元素:

input.group_by { |e| e.delete :size }
#⇒ {
#  "large" => [
#    [0] {
#      :description => "some description 2",
#            :price => 100.0
#    },
#    [1] {
#      :description => "some description 4",
#            :price => 100.0
#    }
#  ],
#  "small" => [
#    [0] {
#      :description => "some description 1",
#            :price => 100.0
#    },
#    [1] {
#      :description => "some description 3",
#            :price => 100.0
#    },
#    [2] {
#      :description => "some description 5",
#            :price => 100.0
#    },
#    [3] {
#      :description => "some description 6",
#            :price => 100.0
#    }
#  ]
# }