2

I am new to programming and I don't understand what the difference is. I am coding in Ruby.

  • basic difference is your sight on many things. For example: you should terminate program(function) if array is empty. `if array.empty?` - good choice. But it doesn't make sense if your parameter `array` is `nil`. So, you prefer to terminate program if array not nil. it can be checked as `unless array` – gaussblurinc Jun 01 '15 at 12:45
  • Possible duplicate of http://stackoverflow.com/questions/4806452/difference-unless-if – Vitalii Elenhaupt Jun 16 '15 at 13:55

3 Answers3

1

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

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

unless is equal to if not

for example:

a= false

unless a
  puts "hello"
end

=> hello

if not a
  puts "hello"
end

=> hello
pangpang
  • 8,581
  • 11
  • 60
  • 96
0

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?
Vitalii Elenhaupt
  • 7,146
  • 3
  • 27
  • 43