Ruby/SQLite3 results as hash returns duplicate data

2.4k views Asked by At

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:

enter image description here

Why is the hash as well as the array being returned when I've set db.results_as_hash = true?

1

There are 1 answers

0
Alex Flores On

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 to true, the inner arrays are turned into the hashes you're seeing.