0

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)
5
  • 2
    Can you be more specific about what going on? What's happening and what do you expect to be happening? That code does in fact get the user input and send it to the method Commented Aug 22, 2017 at 2:42
  • If you need a number, maybe mult.to_f? Commented Aug 22, 2017 at 3:07
  • Note that STDOUT.flush can usually be omitted. Ruby auto-flushes when writing to a terminal device (tty). Commented Aug 22, 2017 at 8:15
  • "I do not know what I am doing wrong" is not a precise enough error description for us to help you. What doesn't work? How doesn't it work? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? Commented Aug 22, 2017 at 8:53
  • Can you provide a precise specification of what it is that you want to happen, including any and all rules, exceptions from those rules, corner cases, special cases, boundary cases, and edge cases? Can you provide sample inputs and outputs demonstrating what you expect to happen, both in normal cases, and in all the exceptions, corner cases, special cases, boundary cases, and edge cases? Commented Aug 22, 2017 at 8:54

2 Answers 2

2

If you need floats, you need to convert the inputs to them:

numb = gets.to_f
...
mult = gets.to_f
...
Sign up to request clarification or add additional context in comments.

Comments

1

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.