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.
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
The pattern /^[0-9]$/ matches one digit.
amount would have to be a regex object to == the regex on the right.
if ‘abc’ == /abc/
puts ‘yes’
else
puts ‘no’
end
regex_obj = /abc/
if regex_obj == /abc/
puts ‘yes’
else
puts ‘no’
end
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
The pattern /^[0-9]$/ matches one digit.
That’s incorrect. The pattern matches: the start of the line, followed
by one digit, followed by the end of the line. So the regex won’t
match a digit in a line containing two digits:
regex = /^[0-9]$/
line = ‘8’
match_obj = regex.match(line)
p match_obj.to_a
line = ‘12’
match_obj = regex.match(line)
p match_obj.to_a
–output:–
[“8”]
[]
You certainly don’t have to use regex’s to convert a string to a float
(or an int). Look at String#to_f and Kernel.Float.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.