0
Unless vs If Else Statement
What do you think about the unless vs if not statements in Ruby
1 Réponse
0
They're a bit weird if you came to ruby from other languages. But, over time, you'll be very comfortable.
Unless lets us write easy to read codes like,
-------------------------------------------------
unless @user.is_authenticated
puts "you're not allowed to be here"
end
-------------------------------------------------
which if we rewrite using 'if' will be
------------------------------
if !@user.is_authenticated
------------------------------
Not very pleasing to look at yeah?
Also, please note that, 'unless' is good to use if your code block don't have any 'else' or 'elsif' condition.
It'll work, but the logic gets a little wonky to grasp at first glance if 'unless' is used with 'elsif' , 'else'
which, if you read the ruby code conventions, you'll find is discouraged
https://github.com/framgia/coding-standards/blob/master/eng/ruby/standard.md
So, in this case
-------- incorrect ----------
unless success?
puts 'failure'
else
puts 'success'
end
-----------------------------
instead use
-------- correct------------
if success?
puts 'success'
else
puts 'failure'
end
-----------------------------