Reputation: 17
I am trying to make this send the user input number to the function but I do not know what I am doing wrong. Can anyone help me?
puts "\n Amount with decimals:\n "
STDOUT.flush
numb = gets
puts "\n Multiplier:\n "
STDOUT.flush
mult = gets
stoque(0.01, numb, 0.5, mult, 1)
Upvotes: 0
Views: 68
Reputation: 114178
If you want Ruby to raise an exception for invalid (i.e. non-decimal) input, you can also use:
numb = Float(gets)
Some examples:1
gets | gets.to_f | Float(gets)
--------+------------+--------------
'1' | 1.0 | 1.0
'.5' | 0.5 | 0.5
'1.2.3' | 1.2 | ArgumentError
'' | 0.0 | ArgumentError
'foo' | 0.0 | ArgumentError
Because of the exception, you probably want to wrap it in a begin-rescue
block, something like:
puts 'Amount with decimals:'
begin
numb = Float(gets)
rescue ArgumentError
puts 'Invalid amount'
retry
end
1 note that gets
includes the newline character "\n"
if the input is entered with return. I've omitted it because trailing newlines are ignored by both, to_f
and Float()
.
Upvotes: 1
Reputation: 168101
If you need floats, you need to convert the inputs to them:
numb = gets.to_f
...
mult = gets.to_f
...
Upvotes: 2