1

Code:

 {   db = Mysql2::Client.new( :host => 'localhost', :username => 'username',
  password => 'password', :database => 'database')

results = db.query("select * from users where exported is not TRUE OR 
  NULL").each(:as => :array)

results.each { | row | puts row[1]}

The results.each line outputs outputs company data, and I want to use each line as an input within an API call. Any ideas as how to do this? Each row should populate an attribute like below.

"requested_item_value_attributes" => {
    "employee_first_name_6000555821" => 'results.each { | row | puts row[0]}',
    "employee_last_name_6000555821" => "results.each { | row | puts row[1]}",
    "hiring_manager_6000555821" => "results.each { | row | puts row[2]}",
    "job_title" => "results.each { | row | puts row[3]}",
    "start_date" => "#results.each { | row | puts row[4]}"
  } 
1
  • If you want to store the results of a collection iteration use map/collect. Commented Mar 31, 2018 at 0:50

3 Answers 3

1

You can use

nameArray = Array.new
nameArray.push(nameToSave)

to add the variable nameToSave to the end of the array nameArray. Just call push for each of your results and you have an array with all your names from your query.

Sign up to request clarification or add additional context in comments.

Comments

0

Use [Array#map] to map the results to an array:

results.map do |row|
  "requested_item_value_attributes" => {
    "employee_first_name_6000555821" => row[0],
    "employee_last_name_6000555821" => row[1],
    "hiring_manager_6000555821" => row[2],
    "job_title" => row[3],
    "start_date" => row[4]
  }
}

or, even better:

results.map do |row|
  "requested_item_value_attributes" => 
    %w[
      employee_first_name_6000555821,
      employee_last_name_6000555821,
      hiring_manager_6000555821,
      job_title,
      start_date
    ].zip(row.take(5)).to_h
  }
}

Comments

0

Use the query method second argument.

results = []
db.query('SELECT * FROM table', results)

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.