The following will create a hash with the username key assigned based on user input:
puts "Hey what's your username?"
username = gets.chomp
user = {
username: username,
pin: 10,
balance: 100
}
puts "Your account is: #{user}"
Similarly, the following will insert a new hash into an array of hashes with the username key assigned based on user input:
def create_user(username)
{
username: username,
pin: 10,
balance: 100
}
end
accounts = []
puts "Hey what's your username?"
username = gets.chomp
accounts.push(create_user(username))
puts "There are #{accounts.length} accounts"
In order to find an element in the array, you can simply iterate through each element and return if that element's username matches the correct username. For example
accounts = [create_user('alice'), create_user('bob')]
def find_by_username(accounts, username)
accounts.each do |user|
return user if user[:username] == username
end
nil
end
puts find_by_username(accounts, 'alice')
puts find_by_username(accounts, 'bob')
puts find_by_username(accounts, 'charles')
This method will iterate through each user and return the user if the username matches the given username. If no such user exists, it will return nil
.
Ruby is nice in that a lot of those types of actions have been abstracted out -- arrays respond to a find
method that returns the first element that matches a code block, or nil if no such element exists. So an alternate implementation of find_by_username
would be
def find_by_username2(accounts, username)
accounts.find do |user|
user[:username] == username
end
end
or more concisely
def find_by_username3(accounts, username)
accounts.find { |user| user[:username] == username }
end
However looping through an array of hashes every time you want to find a user by username is a relatively slow operation. If you were to instead have a hash of hashes, the data structure might look like this:
accounts = {
"alice" => { pin: 312, balance: -100 },
"bob" => { pin: 104, balance: 1000 }
}
and you would be able to find a user with the username of "bob" with accounts["bob"]