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.

3
  • Did you read the docs? rubydoc.info/gems/mysql2/0.2.6/file/README.rdoc Commented Mar 8, 2017 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. Commented Mar 8, 2017 at 13:13
  • Ok..I see. Look at the answers here for some more concrete examples: stackoverflow.com/questions/10836805/… . Maybe those help a little bit to get started. Commented Mar 8, 2017 at 13:36

1 Answer 1

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

8 Comments

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! gyazo.com/bd696eb4cad4262d4849c2be872c7908
I saw the code but what are you trying to accomplish?
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.
I updated my answer. Try those three lines to see if you can print the course names
yeah that worked perfectly (it prints off the course names), is "course_names" now a string array containing the variables?
|

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.