1

Hey I am an absolute ruby noob and hope you could help me. I want to do a lot of SQL-querys with different departments (Department A,B, C....)

I want to save the departments to an array and iteratethrough it, use loops and so on.

This is my old code:

#!/usr/bin/ruby
require 'mysql2'
##Connect to my Database
db = Mysql2::Client.new(:host => "localhost", :username => "MyUserName", :password => "MyPassword", :port => 3306, :database => "MyTest-Database" )

#Mysql querys
sql_A= "SELECT RMKPI FROM `Table1` WHERE `Department` = 'A' "
sql_B= "SELECT RMKPI FROM `Table1` WHERE `Department` = 'B' "

#Execute the querys
results_PO = db.query(sql_A)
results_DevMuM = db.query(sql_A)

This is my Pseudocode:

Array1[A,B,...]
loop
   sql_Array1[x]="SELECT ...WHERE `Department`= Array1[x]"
   Array1[x+1]

How can I do this? Thanks a lot

Gutiu
  • 11
  • 3

1 Answers1

2
DEPARTMENTS = %w|A B C|
results = DEPARTMENTS.map do |department|
  query = "SELECT RMKPI FROM `Table1` WHERE `Department` = '#{department}'"
  [department, db.query(query)]
end.to_h

Now you have a hash of { departments ⇒ results }. To access results for a given department, use:

results['A']

Sidenote: I would suggest you to google for ActiveRecord or any other ROM to simplify and make safer the work with database queries.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160