如何在文件中选择对象.并仅更新此对象



我在file.yml中有这个结构

- !ruby/object:Account
name: Anton
login: Anton1231
password: Antonqwe
age: '37'
card: []

当我sign_in在帐户,我可以添加一些卡。问题-我如何从文件中找到对象,其中登录和密码== login,密码帐户,其中我sign_in和更新仅卡

require 'yaml'
# assume your class looks something like this
class Account
attr_reader :name, :login, :password, :age
attr_accessor :card
end
def read_accounts
File.open('file.yml') { |f| YAML.load_stream(f) }
end
def write_accounts(accounts)
File.open('file.yml', 'r+') do |f|
accounts.each { |a| f.write YAML.dump(a) }
end
end
def update_card(account, card)
account.card << card
end
def find_account(accounts, login, password)
accounts.each do |acct|
return acct if acct.login == login && acct.password == password
end
nil
end
# assume these are set somewhere
@login = 'Anton1231'
@password = 'Antonqwe'
@card = 'a card'
accounts = read_accounts
account = find_account(accounts.first, @login, @password) # accounts.first as accounts is a 2d array
update_card(account, @card) if account
write_accounts accounts

来自这个答案的启发:如何在YAML中读取ruby对象

最新更新