ruby - Why does my if-statement think "5" is greater than "250000"? -
i'm trying run code:
print "how much money want me lend you?" money = gets.chomp if money >"250000" puts "i'm sorry can't lend amount of money" else puts "the involvement rate of 10% monthly" end puts "do accept? yes/no" reply = gets.chomp
the problem if run programme adn write little amount of money such 5, message "i'm sorry can't lend amount of money" appear, when shouldn't because amount not more 250000.
you compare strings, not integers, , lexcographically looked at, "5"
more "250000"
.
"5" > "250000" #=> true "5".to_i > "250000".to_i #=> false improve proposed in reply money.to_i > 250000
here utilize method string#to_i
convert amounts number , comparing expect it.
you can read native, lexicographic order of strings in highly complex article here. compare characters 1 1 left right until first inequality , homecoming result it.
ruby string if-statement comparison-operators
No comments:
Post a Comment