nonopolarity
nonopolarity

Reputation: 150986

Using sqlite3 with Ruby, is there a way to read each row as a hash instead of array?

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.

Upvotes: 4

Views: 558

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

There's results_as_hash setter to get this behavior:

db = SQLite3::Databse.open 'data.db'
db.results_as_hash = true
# ...

Upvotes: 5

Related Questions