1

I have a query in my Ruby file:

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

It treats @mastertest like a 2-D array because, when I print the rows, I get:

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

This prints all code_ver and date from each row.

I am not able to perform any other operations on it. I cannot sort the array nor can I perform a deep copy of the array. I'm guessing it is some MySQL2 type which Ruby considers. How do I convert this to a normal 2-D array?

6
  • Couple things to try: Use @mastertest.class to find out what it is. Try using @mastertest.to_a to convert it to an array if it isn't already. Commented Oct 18, 2012 at 18:56
  • It would help if you told us which library(s) you're using to connect to the database engine. Commented Oct 18, 2012 at 19:30
  • I am using 'mysql' gem to connect to the database.....and I think the result is returned as a mysql result set object. Commented Oct 18, 2012 at 19:31
  • 1
    @lain That's mysql2 gem. I have answered OP's same question once. Seems he juse didn't tried enough. The class of @mastertest is Mysql2::Result. Commented Oct 18, 2012 at 19:32
  • @halfelf : I can't find an example which shows me how to use the @mastertest.to_a . It would be helpful if someone can show me an example. Commented Oct 18, 2012 at 19:38

1 Answer 1

4

The class of @mastertest is Mysql2::Result ; it provides only each and fields methods

Here's an example for one way to convert the results into a 2-D array:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.