使用多个值创建Hash,Ruby和Mysql2 gem

时间:2016-01-14 10:59:48

标签: ruby hash

我正在使用mysql2 gem连接到我的数据库并提取数据。这是一个简单的查询

statement = @db.prepare('SELECT * FROM my_table')
@result = statement.execute

这会返回一个Mysql2::Result对象,我知道要迭代我这样做

@result.each do |r|
  puts r
end

在我的情况下会回复

[
  {"id"=>1,
  "name"=>"Standard",
  "label"=>"Standard",
  "amount"=>100,
  "created_at"=>2010-11-17 11:50:38 +0000,
  "updated_at"=>2010-11-17 11:50:38 +0000,
  "status"=>"active",
  "dataprofileid"=>"0",
  "groupid"=>1},
 {"id"=>2,
  "name"=>"Director Register",
  "label"=>"Director Register",
  "amount"=>150,
  "created_at"=>2010-11-17 11:51:11 +0000,
  "updated_at"=>2010-11-17 11:51:11 +0000,
  "status"=>"active",
  "dataprofileid"=>"18",
  "groupid"=>0}
]

由此我想创建一个看起来像

的哈希
{ "Standard"=> { "id"=>1, "dataprofileid"=> 0 }}

因此,对于每条记录,使用name作为键,然后在其中包含更多键/值。目前我创建了一个常规哈希,其中name为关键,id为值,但我不确定如何进入下一阶段

@credit_ids = []
@credit_names = []
@credit_dataprof = []
  @result.each do |r|
    @credit_names << r['name']
    @credit_ids << r['id']
    @credit_dataprof << r['dataprofileid']
end
@credit_hash = Hash[@credit_names.zip @credit_ids]

4 个答案:

答案 0 :(得分:0)

  1. 将您的数组映射到您实际想要作为值的哈希值。
  2. 使用Enumerable#group_by
  3. 这将允许您按名称获取所有哈希值,并使用完整哈希值。

    或者我没有得到你的问题。 :)

答案 1 :(得分:0)

我在SO上遇到了另一个答案,并提出了有效的方法,希望它有助于其他人

h = Hash.new{|hsh, key| hsh[key] = {} }
@result.each do |r|
  h[r['name']].store 'id', r['id']
  h[r['name']].store 'dataprofileid', r['dataprofileid']
end      

然后返回

{
  "Standard"=> { "id" => 1, "dataprofileid" => "0" },
   "CCJ" => { "id" => 5, "dataprofileid" => "20" }
   # Many more ommitted but you get the idea
}

打开建议,提醒一下

答案 2 :(得分:0)

天真:

@result.map{
  |h| {h["name"] => {"id" => h["id"], "dataprorileid" => h["dataprofileid"]}}
}

会给你:

[
  {"Standard"=>{"id"=>1, "dataprorileid"=>"0"}},
  {"Director Register"=>{"id"=>2, "dataprorileid"=>"18"}}
]

但是如果你想尊重原始结构(保留除"name"以外的键值对),那么:

@result.map{|h| k = h.dup.delete("name"); {k => h}}

会给你:

[
  {"Standard"=>{"id"=>1, "name"=>"Standard", "label"=>"Standard", "amount"=>100, "created_at"=>2016-01-14 20:47:04 +0900, "updated_at"=>2016-01-14 20:47:04 +0900, "status"=>"active", "dataprofileid"=>"0", "groupid"=>1}},
  {"Director Register"=>{"id"=>2, "name"=>"Director Register", "label"=>"Director Register", "amount"=>150, "created_at"=>2016-01-14 20:47:04 +0900, "updated_at"=>2016-01-14 20:47:04 +0900, "status"=>"active", "dataprofileid"=>"18", "groupid"=>0}}
]

答案 3 :(得分:0)

@credit_ids = []
@credit_names = []
@credit_dataprof = []
@credit_hash = Hash.new()
  @result.each do |r|
    @credit_names = r['name']
    @credit_ids = r['id']
    @credit_dataprof = r['dataprofileid']

 @credit_hash  = @credit_hash.merge({@credit_names => {"id" => @credit_ids, "dataprofileid" => @credit_dataprof}})
end

 puts @credit_hash

产生

{"Standard"=>{"id"=>1, "dataprofileid"=>"0"}, "Director Register"=>{"id"=>2, "dataprofileid"=>"18"}}