我的 Ruby 文件中有一个查询:
@mastertest = connection.execute("select code_ver, date from mastertest")
它将 @mastertest
视为二维数组,因为当我打印行时,我得到:
@mastertest.each do |row|
puts row[0] : row[1]
end
这会打印每行的所有 code_ver
和 date
。
我无法对其执行任何其他操作。我无法对数组进行排序,也无法执行数组的深层复制。我猜这是 Ruby 考虑的某种 MySQL2 类型。如何将其转换为普通二维数组?
最佳答案
@mastertest 的类是 Mysql2::Result
;它只提供 each
and fields
methods
下面是将结果转换为二维数组的一种方法的示例:
sql = "select <field1>, <field2> from <table> where <conditions>"
result_array = []
result = ActiveRecord::Base.connection.execute(sql)
index = 0
result.each do |row|
result_array[index] = []
result_array[index] << row[0]
result_array[index] << row[1]
...
result_array[index] << row[n]
...
index += 1
end
关于ruby-on-rails - 从 Ruby 中的二维数组中的 SQL 查询获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12961433/