I would like to know if there is a better way or proper way, to write the 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
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.
alias e puts
def add(name, n)
puts name.to_f / n
def obtain_valid_number(input = obtain_user_input)
end; alias to_valid_number obtain_valid_number
e ‘Please provide a number greater than 0.’
e ‘Please provide the first number.’
@number = obtain_user_input
_ = to_valid_number(@number)
@number = obtain_valid_number
if _ > 0
e ‘The number is
else # Must be lower than 0.
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
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.