I have a query in my ruby file :
@mastertest = connection.execute("select code_ver,date from mastertest")
And I print the result of the query as below:
@mastertest.each do |row|
puts row[0] : row[1]
end
This will print all the code_ver and 'date' which looks like this
2.0 : 2012/12/10
3.1 : 2012/11/03
2.5 : 2012/07/08
1.8 : 2012/12/11
2.5 : 2012/03/01
Now I want to sort this array based on my code_ver, but the problem is ruby does not consider this as an array, it says it is some mysql2 type.
How do I proceed further? I want to either convert this thing to 2-d array or I would want to sort it based on the row[0].
We can easily convert a string to an array in Ruby using the split method. Think of this method as a pair of scissors, and the string you will be converting as a literal piece of string.
Learn to Use the Sort & Sort! Ruby Methods The most basic form of sorting is provided by the Ruby sort method, which is defined by the Enumerable module. Notice that sort will return a new array with the results.
How do I convert a string to array MySQL? MySQL doesn’t support the SQL array data type, so you can’t.
How to Sort Hashes in Ruby. You are not limited to sorting arrays, you can also sort a hash. Example: hash = {coconut: 200, orange: 50, bacon: 100} hash.sort_by(&:last) # 50], [:bacon, 100], [:coconut, 200 This will sort by value, but notice something interesting here, what you get back is not a hash.
You're getting a MySQL result set object in @mastertest and a result set is not an array.
If you're using mysql2, then you should have a Mysql2::Result and that's Enumerable so it has a to_a method:
@mastertest.to_a.sort { ... }
If you're using the mysql gem, then you should have a Mysql::Result and you'll have to convert @mastertest to an Array by hand:
a = [ ]
@mastertest.each { |r| a.push(...) }
a.sort { ... }
Or you could simply let the database do the sorting:
@mastertest = connection.execute('select code_ver, date from mastertest order by code_ver')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With