I have the following code in my app.rb file:
require 'sinatra'
require 'json'
require 'sqlite3'
get '/api/clients' do
db = SQLite3::Database.new "db/db"
db.results_as_hash = true
{clients: db.execute('SELECT * FROM clients')}.to_json
end
Inspecting the results in the browser, we see this:
Why is the hash as well as the array being returned when I've set db.results_as_hash = true
?
Line 584 of the source shows that the records come back as key-value pairs, where the column names are keys and the values are the record's data. It also inserts index values for the headers. Presumably, this is to preserve order dependance in the results hash for older versions of Ruby. Ruby > 1.9 preserves insertion order.
The gem returns a ResultSet as an array of results. If a user sets
results_as_hash
totrue
, the inner arrays are turned into the hashes you're seeing.