0

I want to convert this:

courses = client.query("SELECT LCASE(name) FROM courses")

into an array, so I can easily loop through elements in some existing code, much appreciated.

Kyle
  • 15
  • 8
  • Did you read the docs? http://www.rubydoc.info/gems/mysql2/0.2.6/file/README.rdoc – Casper Mar 08 '17 at 12:55
  • yeah I have read through the relevant areas of what you have linked me. I feel really stupid asking such a basic question, but I think I just need to see a working example to wrap my head around it. – Kyle Mar 08 '17 at 13:13
  • Ok..I see. Look at the answers here for some more concrete examples: http://stackoverflow.com/questions/10836805/how-can-i-iterate-through-a-mysql-result-set . Maybe those help a little bit to get started. – Casper Mar 08 '17 at 13:36

1 Answers1

1

If that courses object is a Mysql2::Result you already can because it includes the Enumerable module. So you can use each, select, first and all the others methods from the module. Anyway, if you actually want an array object

courses = client.query("SELECT LCASE(name) FROM courses").to_a

to_a is from Enumerable module as well

courses = client.query("SELECT LCASE(name) AS name FROM courses")
course_names = courses.map { |course| course['name'] }
course_names.each { |course_name| puts course_name }
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • doesn't seem to work still, it says something about hash converting to a string, I will show you how I am using it to see if you can spot the errors of my ways, thanks in advance you are a life saver! https://gyazo.com/bd696eb4cad4262d4849c2be872c7908 – Kyle Mar 08 '17 at 13:05
  • I saw the code but what are you trying to accomplish? – Ursus Mar 08 '17 at 13:09
  • Basically I want the variable "courses", to be an array that contains a bunch of strings from one of the columns in my database. Thanks again. – Kyle Mar 08 '17 at 13:12
  • I updated my answer. Try those three lines to see if you can print the course names – Ursus Mar 08 '17 at 13:20
  • yeah that worked perfectly (it prints off the course names), is "course_names" now a string array containing the variables? – Kyle Mar 08 '17 at 13:30
  • It's an array of strings from your database, table courses, field name, with LCASE function applied. – Ursus Mar 08 '17 at 13:31
  • So where you have "puts course_name" could I do this to write the course names to an array: course_names.each { course_names_array = |course_name| } – Kyle Mar 08 '17 at 13:37
  • Its values are just strings – Ursus Mar 08 '17 at 13:39