ruby将嵌套数组转换为哈希

时间:2015-05-29 11:14:16

标签: arrays ruby hash enumerable

是否有一种优雅的方式来转换表单的嵌套数组

[["a", 1], ["a", 2], [nil, 3], [nil, 4], ["b", 6], ["b", 8]]

进入表单的哈希

{"a" => [1,2], nil => [3,4], "b" => [6,8]}

5 个答案:

答案 0 :(得分:3)

这是一种方式:

arr = [["a", 1], ["a", 2], [nil, 3], [nil, 4], ["b", 6], ["b", 8]]

h = Hash.new {|hash, key| hash[key] = []}
arr.each {|e| h[e[0]] << e[1]}
p h #=> {"a"=>[1, 2], nil=>[3, 4], "b"=>[6, 8]}

答案 1 :(得分:2)

ary = [['a', 1], ['a', 2], [nil, 3], [nil, 4], ['b', 6], ['b', 8]]

ary.group_by(&:first).
# => { 'a' => [['a', 1], ['a', 2]], nil => [[nil, 3], [nil, 4]], 'b' => [['b', 6], ['b', 8]] }
  map {|k, v| [k, v.map(&:last)] }.
# => [['a', [1, 2]], [nil, [3, 4]], ['b', [6, 8]]]
  to_h
# => { 'a' => [1, 2], nil => [3, 4], 'b' => [6, 8] }

答案 2 :(得分:1)

一种方法可能是:

class PostsController extends AppController
{

        public $name = 'Posts';
        public $helpers = array('Html', 'Form', 'Session');
        public $components  = array('RequestHandler');
public function ajaxAdd()
    {
        $this->autoRender=false;
          if($this->RequestHandler->isAjax()){
             Configure::write('debug', 0);
          }
            if(!empty($this->data)){
                $inputData = array();
                $inputData['Post']['title'] = $this->data['Post']['ajaxtitle'];
                $inputData['Post']['body'] = $this->data['Post']['ajaxbody'];
                $data = $this->Post->findByTitle($inputData['Post']['title']);
                $this->Post->create();
               if(empty($data))
               {                   
                  if($this->Post->save($inputData))
                      return "success"; 
                }else
                {
                 return "error";
               }
            }
        }
}

答案 3 :(得分:0)

array.each_with_object({}){|a, h| (h[a.first]||=[] )<< a.last }

答案 4 :(得分:-1)

ary = [['a', 1], ['a', 2], [nil, 3], [nil, 4], ['b', 6], ['b', 8]]
ary.group_by(&:first).map {|k, v| {k => v.map(&:last)} }