How to obtain result as array of Hashes in Ruby (mysql2 gem)

ddinchev picture ddinchev · Oct 22, 2012 · Viewed 12.4k times · Source

I'm using Ruby's mysql2 gem found here: https://github.com/brianmario/mysql2

I have the following code:

client = Mysql2::Client.new(
  :host => dbhost, 
  :port => dbport, :database => dbname,
  :username => dbuser, 
  :password => dbpass)
sql = "SELECT column1, column2, column3 FROM table WHERE id=#{id}"
res = client.query(sql, :as => :array)
p res # prints #<Mysql2::Result:0x007fa8e514b7d0>

Is it possible the above .query call to return array of hashes, each hesh in the res array to be in the format column => value. I can do this manually but from the docs I was left with the impression that I can get the results directly loaded in memory in the mentioned format. I need this, because after that I have to encode the result in json anyway, so there is no advantage for me to fetch the rows one by one. Also the amount of data is always very small.

Answer

steenslag picture steenslag · Oct 22, 2012

Change

res = client.query(sql, :as => :array)

to:

res = client.query(sql, :as => :hash)

As @Tadman says, :as => :hash is the default, so actually you don't have to specify anything.