Question

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}
Was it helpful?

Solution

You have two mistakes in your code:

1) You have two closing braces:

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

2) map() returns an array, and you don't save the array anywhere, so ruby discards it.

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

p records

Here's the proof:

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}]

Note that your output indicates the 'count' field is already an int, so calling to_i() is redundant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top