Morton Goldberg
11/2/2007 5:22:00 AM
On Nov 2, 2007, at 12:47 AM, Feng Tien wrote:
> Building a Bank class, deposits must be floating, so if it has any
> letters, it will tell the user it needs numbers
>
>
> if amount == /^[0-9]$/
> deposit_to_acct(amount,current_account)
> puts 'You have deposited ' + amount.to_s
>
> else
> puts 'Must be a number, alphabet bank is next door to your
> right'
>
> end
>
> it goes straight to the else statement, never executes the
> deposit_to_acct method.
>
> What part am I doing wrong?
I would say that you need a better understanding of regular
expressions and how they are matched to strings in Ruby. The expression
amount == /^[0-9]$/
is an equality test and will always be false if 'amount' is a string.
Consider the following examples:
<code>
# the following perform equality tests, not string to regular
expression matching
123 == /^[0-9]$/ # => false
'123' == /^[0-9]$/ # => false
/^[0-9]$/ == /^[0-9]$/ # => true
/^[0-9]$/.equal?(/^[0-9]$/ )# => false
# the following perform regular expression matching
'123' =~ /^[0-9]$/ # => nil (match fails because RE only accepts one
digit)
'3' =~ /^[0-9]$/ # => 0 (match succeeds)
'123' =~ /^[0-9]+$/ # => 0 (match succeeds)
'123X' =~ /^[0-9]+$/ # => nil (match fails)
</code>
Regards, Morton