1

I am trying to parse some output from a query using the mysql2 gem.

Previously, I would use:

response = JSON.parse(response.body)
a = response.map{|s| {label: s['Category'], value: s['count'].to_i} }

Now with the mysql2 query:

results = db.query(sql)
results.map do |row|
  puts row
end

Output

{"Category"=>"Food", "count"=>22}
{"Category"=>"Drinks", "count"=>12}
{"Category"=>"Alcohol", "count"=>9}
{"Category"=>"Home", "count"=>7}
{"Category"=>"Work", "count"=>2}

'Category' to ':label' and 'count' to ':value'.

results = db.query(sql)
results.map do |row|
  {label: row['Category'], value: row['count'].to_i} }
end

Desired Output

{:label=>"Food", :value=>22}
{:label=>"Drinks", :value=>12}
{:label=>"Alcohol", :value=>9}
{:label=>"Home", :value=>7}
{:label=>"Work", :value=>2}
4

1 回答 1

2

您的代码中有两个错误:

1)你有两个右括号:

                                               #   HERE
                                               #   | |
results.map do |row|                           #   V V
  {label: row['Category'], value: row['count'].to_i} }
end

2) map() 返回一个数组,并且您不会将数组保存在任何地方,因此 ruby​​ 会丢弃它。

records = results.map do |row|
  {label: row['Category'], value: row['count'].to_i }
end

p records

这是证明:

mysql> select * from party_supplies;
+----+----------+-------+
| id | Category | count |
+----+----------+-------+
|  1 | Food     |    22 |
|  2 | Drinks   |    12 |
+----+----------+-------+
2 rows in set (0.00 sec)

.

require 'mysql2'

client = Mysql2::Client.new(
  host: "localhost", 
  username: "root",
  database: "my_db",
)

results = client.query("SELECT * FROM party_supplies")


records = results.map do |row|
  { label: row['Category'], value: row['count'] }
end

p records


--output:--
[{:label=>"Food", :value=>22}, {:label=>"Drinks", :value=>12}]

请注意,您的输出表明“count”字段已经是一个 int,因此调用 to_i() 是多余的。

于 2013-09-05T02:58:30.230 回答