jwfearn jwfearn - 7 months ago 12
Ruby Question

How to get rows as Arrays (not Hashes) in Sequel ORM?

In the Sequel ORM for Ruby, the

Dataset
class has an
all
method which produces an Array of row hashes: each row is a Hash with column names as keys.

For example, given a table T:

a b c
--------------
0 22 "Abe"
1 35 "Betty"
2 58 "Chris"


then:

ds = DB['select a, b, c from T']
ah = ds.all # Array of row Hashes


should produce:

[{"a":0,"b":22,"c":"Abe"},{"a":1,"b":35,"c":"Betty"},{"a":2,"b":58,"c":"Chris"}]


Is there a way built in to Sequel to instead produce an Array of row Arrays, where each row is an array of only the values in each row in the order specified in the query? Sort of how
select_rows
works in ActiveRecord? Something like this:

aa = ds.rows # Array of row Arrays


which would produce:

[[0,22,"Abe"],[1,35,"Betty"],[2,58,"Chris"]]


Note: the expression:

aa = ds.map { |h| h.values }


produces an array of arrays, but the order of values in the rows is NOT guaranteed to match the order requested in the original query. In this example,
aa
might look like:

[["Abe",0,22],["Betty",1,35],["Chris",2,58]]

Answer

If you want just an array of array of values...

DB['select * from T'].map { |h| h.values }

seems to work

UPDATE given the updated requirement of the column order matching the query order...

cols= [:a, :c, :b]
DB[:T].select{cols}.collect{ |h| cols.collect {|c| h[c]}}

not very pretty but guaranteed order is the same as the select order. There does not appear to be a builtin to do this. You could make a request for the feature.