Data Validation in Ruby

Hi there,

I am a newbie ruby programmer. I created a simple banking system with a
database. I can add new records to the database, deposit, withdraw and
transfer money from one account to another via the console, like so:

a = Account.new
a.account_holder = ‘Steve’
a.deposit(40)

I would like to modify my program to do the following:

  1. Allow for decimal values i.e. a.deposit(30.35)
  2. Allow for the user to put a dollar sign in front of the dollar amount
    i.e. a.deposit(‘$55.34’)
  3. Should not allow the user to withdraw/transfer more money than is in
    the account
  4. Handle invalid input. i.e. a.deposit(‘cows’), a.account_holder=nil,
    a.withdraw(-55)

Any ideas??

What do you have so far? What does your Account class look like? What
kind of database are you using? How are you connecting to the database?
What data types and constraints are you using within the database?

Thanks Joel,

Actually there is no database, my bad. This is my code for the banking
system:

class Account
def initialize(balance, name, account_number)
@balance = balance
@name = name
@account_number = account_number
end

def deposit(amount)
@balance += amount
end

def withdraw(amount)
@balance -= amount
end

def balance
puts "Name: " + @name
puts "Account number: " + @account_number.to_s
puts "Balance: " + @balance.to_s
end

def transfer(amount, target_account)
@balance -= amount
target_account.deposit(amount)
end

def status
return @balance
end
end
a = Account.new(50, “Job”, 01234)
puts a.balance

a = Account.new(50.51, “Hopkins”, 012)
a.deposit(’$1.22’)
a.withdraw(5.80)
puts a.balance
#############################################

str = ‘$55.34’
str.gsub(/[$]/, “”).to_f

N.B: I have modified my code a little bit. To this point I have been
able to solve 1 to 2. I am still struggling with 3 thru 4.

I appreciate your time.

Ok, here are some ideas to get you started:

  1. You want to be very careful with this in case you intend to use
    multiple currencies, but a simple way to extract a number from a string
    would be to use Regexp and a type conversion:

Float ‘$55.34’[/\d+.?\d*/]
=> 55.34

This Regexp ignores the entry of negative numbers, which might be useful
in case someone tries to “withdraw” -10000, but if you ever want to use
negatives in the input you’ll need to change this.

  1. all you need is a few judiciously placed conditionals, something like
    this:

def withdraw(amount)
raise ‘Insufficient Funds’ if amount > @balance
@balance -= amount
end

  1. You’ll need to do this by checking the method arguments before
    continuing through the method, the same as in 3).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs