Shorthand unless/if not correctly documented



Obviously there is an alternative "shorthand" syntax to unless and if:

print "Go" unless problem

While this is used in "15. Unless" in the code example, it is neither documented in the "hint" nor in the Glossary.

I feel that is confusing and that it should be explicitly documented.



I came here looking for help with how to use the "unless" function. I had written this code (below) only to get the error: "comparison of String with 0 failed" when entering any value. What has gone wrong?

puts "Enter a number larger than zero"
val1 = gets.chomp
if val1<0
problem = true
print "Good listening!" unless problem


get.chomp returns a string - not a number.
This is why the comparison is failing.
You need to convert val1 into a float (or an integer).

if val1.to_f < 0

Note: To be 100% sure you would actually need to check the input for validity, since the user might not respond with a number.

If there is not a valid number at the start of str, 0.0 is returned.

That means you probably should use:
if val1.to_f <= 0
… to also catch the zero as wrong input and that should cover non numeric input as well.


Ah, makes sense. Thanks!