Reputation: 29
I am new to programming and I don't understand what the difference is. I am coding in Ruby.
Upvotes: 2
Views: 620
Reputation: 7326
One of the goals of Ruby language is to become more closer to the real English. And keywords if
and unless
are really good examples of that. Look at this:
if animal.can_speak?
animal.say 'Woof!'
end
# moreover, it can be transformed in one-line, which looks pretty awesome:
animal.say 'Woof!' if animal.can_speak?
unless
is an opposite of the if
and instead of writing:
if not animal.can_speak?
puts "This animal can't speak"
end
we can use unless
, that usually considered as more natural way:
unless animal.can_speak?
puts "This animal can't speak"
end
# it also has one-line approach:
puts "..." unless animal.can_speak?
Upvotes: 0
Reputation: 8821
unless
is equal to if not
for example:
a= false
unless a
puts "hello"
end
=> hello
if not a
puts "hello"
end
=> hello
Upvotes: 0
Reputation: 308733
if should be obvious: execute a block of code if the condition is true.
unless is the opposite: execute a block of code if the condition is false.
http://www.codecademy.com/glossary/ruby/if-unless-elsif-and-else
Upvotes: 1