I would like to know if there is a better way or proper way, to write the below
code below.
A lot can be written better in ruby.
I think your code is semi-ok for a first try.
What I would do is to get rid of the repetition. Since you repeat
the same action, you should capture that part and re-use it.
I also read somewhere that using too many exceptions are bad?
It is a way of control flow but you should ask whether you would
need it in your current setup.
I do not think that you would need it in your current setup
because you are in full control over the input and can sanitize
it.
I would recommend to use a class too - while a class has a
slight additional layer (class Foo; end) around the code,
the long-time benefit is really really helping you design
SIMPLER code in the long run.
Example:
class GrabNumbers
alias e puts
def initialize
run
end
def add(name, n)
puts name.to_f / n
end
def obtain_user_input
$stdin.gets.chomp
end
def obtain_valid_number(input = obtain_user_input)
input.to_i
end; alias to_valid_number obtain_valid_number
def please_provide_a_number_greater_than_zero
e ‘Please provide a number greater than 0.’
end
def run
e ‘Please provide the first number.’
loop {
@number = obtain_user_input
case @number
when ‘q’,‘exit’,‘break’
break
end
_ = to_valid_number(@number)
case _
when 0
please_provide_a_number_greater_than_zero
@number = obtain_valid_number
else
if _ > 0
e ‘The number is '+_.to_s+'
.’
break
else # Must be lower than 0.
please_provide_a_number_greater_than_zero
end
end
}
end
end
GrabNumbers.new
Don’t assume that the above is great code… I just threw
it together in about 5 minutes or so. It kinda works too
though, so it’s not awful. You of course can still use
Integer() in your own code - I just did not think that
it was necessary.
If you have not yet written a class in ruby, try it -
the concept is quite simple and once you understood
it, ONCE, you can apply it for the rest of your life
to all of ruby, just about.
There are also some simpler ways to write the above
by the way, I just have an awkward style in ruby -
feel free to find a style that sits well for you.
I should also add that, once it is a class, the part
that you want to change lateron, becomes really super
simple.
Also always try to write minimal test cases for your
class there, so that you can run these tests lateron
when you make some changes. For a simple class like
this it would be overkill, but for more complex use
cases, minimal tests are good.