ruby-on-rails - 从 Ruby 中的二维数组中的 SQL 查询获取结果

标签 ruby-on-rails ruby arrays multidimensional-array

我的 Ruby 文件中有一个查询:

@mastertest = connection.execute("select code_ver, date from mastertest")

它将 @mastertest 视为二维数组,因为当我打印行时,我得到:

@mastertest.each do |row|
puts row[0] : row[1]
end

这会打印每行的所有 code_verdate

我无法对其执行任何其他操作。我无法对数组进行排序,也无法执行数组的深层复制。我猜这是 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/

相关文章:

ruby-on-rails - :autosave property of has_many associations broken in Rails 2. 3.4?

ruby-on-rails - 保持 rake 作业运行

ruby - Dashing 不能在 Heroku 上运行

arrays - 使用随机数组添加 Java 排序算法

ruby-on-rails - 我的 application.js 无法工作并且 application.css 无法在 Rails 中更新

ruby-on-rails - rails 5 : rename table migration

ruby-on-rails - Ruby on Rails 按 id(和版本?)排序

ruby-on-rails - 思考狮身人面像,联想不起作用

c# - 将数字字符串转换为数字数组 C#?

字符串可以用作数组索引吗?