我有一组数组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]]
有可能吗?
答案 0 :(得分:6)
答案 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
。