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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With