0

I have made a fake CRUD-based bank account manager that can create new accounts and also destroy them using the terminal. Just to make clear, this is not a Rails application. I've made a 'fake' MVC structure in vanilla Ruby to understand the basic concept.

I'm having difficulty trying to delete a class instance when the 'destroy' criteria has been satisfied. In this case, if a user wants to destroy a bank account, they need to specify the bank account number of the class instance. I'm not sure if my Ruby method is just incorrectly trying to handle the deletion or if what I am doing is not possible.

Here is method so far:

def delete(account_number)
  @accounts.each_with_index do |account, index|
    account.include?(account_number) ? account.delete_at(index) : "No account found"
  end
end

Here is the error message I am being presented:

`block in delete': undefined method `include?' for #<Account:0x00007fe82c8926c0 @name="test", @account_number="12345", @sort_code="040004", @balance="1234.5"> (NoMethodError)

Essentially, my end goal is for my method to scan the class instance, match @account_number with the account_number passed in the terminal and delete the instance completely. I've been able to do this using 'index' i.e. "delete the 1st in the list" (index + 1) but want to try a more advanced way.

N.B: @accounts is an instance variable set as an array to store the instances.

6
  • Why not account = Account.find_by(account_number: account_number) account.delete if account.present? Commented Apr 14, 2022 at 2:47
  • Ah, I probably left an important part out. The @accounts is an instance variable set as an array in which these instances are being stored. How would I go about using your solution to delete once find_by works? Commented Apr 14, 2022 at 2:50
  • 1
    Maybe start with account = @accounts.find { |a| a.account_number == account_number } to find the account. Commented Apr 14, 2022 at 3:36
  • ...and then, if account.nil? => false, @accounts.delete(account). Commented Apr 14, 2022 at 3:49
  • 1
    As a rule of thumb: don't alter a collection while traversing it. Commented Apr 14, 2022 at 9:50

1 Answer 1

1

I would use Array#delete_if when I want to delete an account with a certain name for an array of accounts.

def delete(account_number)
  @accounts.delete_if { |account| account.number == account_number }
end

If there is no matching account found then this method keeps the @accounds array unchanged.

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

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.