The Banking Select an Account Problem

In this exercise I was asked to obtain [first_name], [last_name], and [email] for 5 people. Those people should be entered into an array of hashes and then I should be able to recall a person by giving the account number back to the program which had been randomly created into a 10 digit number.

The 5.times loop was the choice in order to capture info, but when it came time to generate a random number that always contained 10 digits (leading zeros if necessary) I had to get a little fancier. Ruby doesn’t have a built in way of formatting this with a simple method. One way I saw was to use right justification and ply in leading a number of zeros based on length of the number string. I used a different approach with center justification.

# random 10 digit number
acct_number = rand(9999999999).to_s.center(10, rand(9).to_s).to_i

The next fun problem was to retrieve the info. I used the Enumerable#select method like so:

# returns a person array with a single person's hash inside
person = people.select { |person| person["acct_number"] == account_lookup }

And here’s the complete code:

people = []
5.times {
 puts "Enter the person's first name:"
 first_name = gets.chomp
 puts "Enter the person's last name:"
 last_name = gets.chomp
 puts "Enter the person's email:"
 email = gets.chomp
 until email.include?("@") && email[-4..-1] == ".com" && email.include?(" ") == false
 puts "#{email} is not a valid email address. Enter a valid email address:"
 email = gets.chomp
 end
 acct_number = rand(9999999999).to_s.center(10, rand(9).to_s).to_i
 people << { "first_name" => first_name, "last_name" => last_name, "email" => email, "acct_number" => acct_number }
 puts "USER# #{acct_number} ADDED."
}

people.each { |person|
 puts "FIRST NAME: #{person["first_name"]}"
 puts "LAST NAME: #{person["last_name"]}"
 puts "EMAIL: #{person["email"]}"
 puts "ACCOUNT NUMBER: #{person["acct_number"]}"
}

puts "Enter an account number to look up:"
account_lookup = gets.chomp.to_i

person = people.select { |person| person["acct_number"] == account_lookup }

puts "FIRST NAME: #{person[0]["first_name"]}"
puts "LAST NAME: #{person[0]["last_name"]}"
puts "EMAIL: #{person[0]["email"]}"
puts "ACCOUNT NUMBER: #{person[0]["acct_number"]}"
The Banking Select an Account Problem