数组的Ruby哈希从数组中删除第一个元素

时间:2015-12-09 15:43:22

标签: arrays ruby

我有一组数组arr = [["U6342", "2015-01-12", "Account"],other similar arrays]

然后我按第一个元素

分组
arr.group_by(&:first)
 => {"U6342"=>[["U6342", "2015-01-12", "Account"],other similar arrays]]

但我想从所有数组中删除第一个元素并获取

 => {"U6342"=>[[ "2015-01-12", "Account"],other similar arrays]]

有可能吗?

4 个答案:

答案 0 :(得分:6)

可能会shift所需的元素。

arr.group_by &:shift

您是否不想修改原始数组:

arr.map(&:dup).group_by &:shift

答案 1 :(得分:1)

我认为其他一些回答者正在过度思考它:

arr = [ ["U6342", "2015-01-12", "Account"],
        ["U1234", "2015-02-12", "Foo"],
        ["U6342", "2015-03-12", "Bar"],
        ["U1234", "2015-04-12", "Qux"] ]

arr.group_by(&:shift)
# => { "U6342" => [ [ "2015-01-12", "Account" ],
#                   [ "2015-03-12", "Bar"     ] ],
#      "U1234" => [ [ "2015-02-12", "Foo"     ],
#                   [ "2015-04-12", "Qux"     ] ]
#    }

Array#shift从数组中删除第一个元素并返回它。 arr.group_by(&:shift)arr中的每个元素中删除第一个元素,并从中删除。

答案 2 :(得分:0)

您可以使用此代码

arr = [["U6342", "2015-01-12", "Account"], ["U6343", "2015-02-12", "Bank"]]

Hash[arr.map{|ar| [ar.first, ar[1..-1]]}]
# => {"U6342"=>["2015-01-12", "Account"], "U6343"=>["2015-02-12", "Bank"]}

或使用"修改"原始arr变量

Hash[arr.map{|ar| [ar.shift, ar]}]

我希望这会有所帮助

答案 3 :(得分:0)

您不必使用group_by分组:

arr = [["dog", "named", "Bert"],
       ["cat", "named", "Boots"],
       ["dog", "named", "Hank"],
       ["pig", "named", "Porky"],
       ["cat", "named", "Tiger"]]

arr.each_with_object(Hash.new { |h,k| h[k]=[] }) { |(f,*a),h| h[f] << a }
  # => {"dog"=>[["named", "Bert"], ["named", "Hank"]],
  #     "cat"=>[["named", "Boots"], ["named", "Tiger"]],
  #     "pig"=>[["named", "Porky"]]} 

请注意,这并不会改变arr