4

I am using sqlite3 as follows:

db = SQLite3::Database.open "data.db"

stm = db.prepare "SELECT * FROM COMPANIES"
rs = stm.execute

while (row = rs.next) do
    name = row[1]

that is, the row is an array instead of a hash. Is there a way to read it as a hash, so that

row[:name]
row[:address]

is the data. That's because in the future, if the table has a different order of columns, row[3] may become row[5], so row[:address] is much more definite.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • 2
    Rather than use the SQLite gem, I'd recommend one of the ORMs that help insulate you from a DBM-specific language. SQLite is nice, but if your DB needs grow having to rewrite all your calls for a different DBM is a major pain. I like [Sequel](https://sequel.jeremyevans.net/) because it's very agnostic and very capable. https://sequel.jeremyevans.net/rdoc/files/doc/cheat_sheet_rdoc.html is a good overview. – the Tin Man Dec 09 '19 at 07:33

1 Answers1

5

There's results_as_hash setter to get this behavior:

db = SQLite3::Databse.open 'data.db'
db.results_as_hash = true
# ...
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91