Paul Thompson Paul Thompson - 2 months ago 9
Ruby Question

Ruby: if boolean true return first_name from same row (in csv file)

I'm able to work this statement to a point but I'd like to add another outcome. How to get the statement to return a value from the same row (headed 'first_name') in the CSV if the boolean statement returns true?

CSV File for example

def customer_check(user_pin)

x = false

CSV.read('customers.csv', headers: true).any? do |row|
x = true if row['pin'] == user_pin and row['work_here'] == "YES"
yellow = row['first_name']

if x == true then
puts "Welcome back #{yellow}."
sleep(1.5)
else
puts "login failed. Please try again in 3 seconds..."
sleep(3.0)
login_start
end
navigation_menu
end

Answer

If you are 100% sure the pins in your csv are unique you could try this

def customer_check(user_pin)

  user = CSV.read('customers.csv', headers: true).detect { |row| 
      row['pin'] == user_pin && row['work_here'] == "YES"
  }

  if user
    puts "Welcome back #{user['first_name']}."
    sleep(1.5)
  else
    puts "login failed. Please try again in 3 seconds..."
    sleep(3.0)
    login_start
  end

  navigation_menu

end 

Variable user will be initialized as the corresponding row of the .csv for which the conditional is true. Otherwise it's value will be nil:

detect method according to documentation:

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

If no block is given, an enumerator is returned instead.

Bear in mind that you might have to ensure that row['pin'] matches your user_id data type as it may come in as a String in which case you'd have to row['pin'].to_i == user_pin