What is the unless command for in Ruby

Asked

Viewed 3,880 times

1

Can anyone explain how this command works unless in Ruby?

ruby_is_ugly = false
puts "Ruby não é feio!" unless ruby_is_ugly

Got out

"Ruby não é feio!"
  • What do you mean? There’s nothing on the way out.

  • @M8n I copied wrong. I fixed it. Right is false, not true as it was. I hadn’t had coffee yet. ;)

2 answers

4


In a nutshell it is an otherwise if, where it executes the content within the conditional case the condition don’t be true.

Example:

#!/usr/bin/ruby

x = 1 
unless x == 2
   puts "x é diferente de 2"
 else
   puts "x é igual a 2"
end

Source:

1

unless is equivalent to using if not, using unless or if not (if ! condition) is a personal preference. I personally use unless when a Else.

  • 1

    Hadn’t that already been said in the other reply? I didn’t understand what you wanted to complete with your.

  • @Andeson Carlos Woss, more or less, just wanted to express in a slightly different way. What’s wrong with the answer?

  • As far as content is concerned, I could go into more detail and give examples, but I have only referred to the point where I consider it unnecessary to give a new answer which adds nothing to the discussion. Everything you said was said in the other reply. If you edit your reply and add something that adds to content, ok. In fact, I’m not the one who denied the answer.

  • I get it, it’s just that before answering, even though doubt was simple, I did a good search in the English OS and it seemed to me to make sense to add an explanation, even though it seemed redundant.

  • You can leave if you want. This is just my opinion. If you think it is valid, let.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.