There's a lot to your question so I recommend that you read How do I ask a good question? to help you get answers in the future. I'll go through each of your questions and try to provide answers to point you in the right direction.
The is_a?
method works by accepting a class as a parameter and returning boolean. For example:
'foo'.is_a?(String)
=> true
1234.is_a?(Integer)
=> true
'foo'.is_a?(Integer)
=> false
1234.is_a?(String)
=> false
1.234.is_a?(Float)
=> true
The .to_i
method is defined on the String class and will convert a string to an Integer. If there is no valid integer at the start of the string then it will return 0
. For example:
"12345".to_i #=> 12345
"99 red balloons".to_i #=> 99
"0a".to_i #=> 0
"hello".to_i #=> 0
The .to_s
method on the Integer
class will return the string representation of the Integer. For example:
1234.to_s
=> '1234'
The same is true of Float
:
1.234.to_s
=> '1.234'
Now let's take a look at your code. When I run it I get SyntaxError: (eval):4: Can't escape from eval with break
which is happening because break
has nothing to break out of; it isn't used to break out of an if
statement but is instead used to break out of a block. For example:
if true
break
end
raises an error. But this does not:
loop do
if true
break
end
end
The reason is that calling break
says "break out of the enclosing block," which in this case is the loop do ... end
block. In the previous example there was no block enclosing the if
statement. You can find more detailed explanations of the behavior of break
elsewhere on stackoverflow.
Your final question was "I just want to know how to check for any of the 3 values and handle them accordingly." This answer explains how to do that but the code example is written in a way that's hard to decipher, so I've rewritten it below in an expanded form to make it clear what's happening:
regular_price = gets.chomp
begin
puts Integer(regular_price)
rescue
begin
puts Float(regular_price)
rescue
puts 'please enter your price as an Integer or Float'
end
end
What this code does is first it attempts to convert the string regular_price
to an Integer. This raises an exception if it can't be converted. For example:
Integer('1234')
=> 1234
Integer('1.234')
ArgumentError: invalid value for Integer(): "1.234"
Integer('foo')
ArgumentError: invalid value for Integer(): "foo"
If an exception is raised then the rescue
line stops the exception from being raised and instead continues executing on the next line. In this case, we're saying "if you can't convert to Integer
then rescue
and try to convert to Float
." This works the same way as converting to Integer
:
Float('1.234')
=> 1.234
Float('foo')
ArgumentError: invalid value for Float(): "foo"
Finally, we say "if you can't convert to Float
then rescue
and show an error message."
I hope this helps and answers your questions.