Colton Haugrud Colton Haugrud - 2 months ago 11
Ruby Question

Ruby string "#to_i" returning "0."

As the title states, the string to_i is returning the number 0 whenever the input is lead by anything other than an integer. For example, if I input "$32" it returns 0, but if I put 32, it returns a number. I found another post that said to_i only accepts digits, but did not offer an alternative solution. My question is, is there a way around this? I want the user to be able to input a "$" before their number. As it stands, my code looks like this:

puts"What is the cost of a gallon of paint?"

cost=gets.chomp.to_i

total_cost=cost*@gallons_needed"


Forgive me if this is a basic question, I started with Ruby and programming as a whole about a week ago. So, I'm extremely new to all of this. Thanks in advance for any and all help!

Answer

You can use scan with regex and join

'$32'.scan(/\d/).join('').to_i
#=>32

in your example:

cost= gets.chomp.scan(/\d/).join('').to_i

total_cost=cost*@gallons_needed"
Comments