Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Mysql2 return result hash using symbols instead of strings as keys

I'm using Mysql2 Gem with Ruby and I have the result turned into a hash using

sql = "SELECT * FROM ... WHERE ... "

results = ActiveRecord::Base.connection.execute(sql)

results.each(:as => :hash) do |row|
  finalresults << row
end

But this returns the hash with strings as the keys. What I want is for the hash to use symbols as the keys, since I have heard that generally symbols are more efficient. Anyone know how to do this in an efficient way that doesn't involve looping over the keys after the result is returned? Note that some queries of mine may produce large sets of data.

So, instead of

{'id'=>19201, 'name'=>'Foo', 'age'=>30}

I want,

{:id=>19201, :name=>'Foo', :age=>30}

Thanks in advance

like image 266
StanMarsh Avatar asked Sep 19 '25 00:09

StanMarsh


1 Answers

You can use Hash#with_indifferent_access. While I'm not sure if there is a way to results be automatically accessed indiferently, most likely this is how it would be implemented under the hood, so no performance penalties.

results.each(:as => :hash) do |row|
  finalresults << row.with_indifferent_access
end
like image 178
fotanus Avatar answered Sep 20 '25 16:09

fotanus