Skip to main content
Ruby

Ruby – if and unless

By October 11, 2013No Comments



You may well be used to the conditional if statement in almost all programming, if not all. In ruby if does exist and we will use it. We also have a new conditional operator to dispense and that is unless. We will use unless in this tutorial with examples and explanation of why we may use it.

The operator unless can be used in place of if not statements and they are designed to simplify you code and help its readability. Consider the following examples:

if not File.exists?('somefile')
  puts "The file does not exist"
end
puts "The file does not exist" unless File.exists('somefile')

In both examples the message only prints if the file does not exist but the code is shorter and easier to read in the newer ruby syntax. We can use either; however ruby is designed as a more straight forward way of programming so if we only ever code in the way we are used to we do not see the benefits.

In the next example we look at testing to see if a directory exits, if is does not we create it and then move to that directory. To create and move into the directory we rely on a module fileutils.

#!/usr/bin/ruby
require 'fileutils'
rubydir = ENV['HOME'] + '/ruby'
FileUtils.mkdir(rubydir) unless File.directory?(rubydir)
FileUtils.chdir(rubydir)

Line by line

1. The shebang points to the ruby program
2. We include the additional module fileutils, using the operator require means that it has to load successfully
3. We then populate the local variable rubydir by expanding the environment variable HOME and appending the path /ruby. So in Linux the variable rubydir may look like /home/user/ruby
4. We then use the method mkdir from the class FileUtils, this comes from the required module. This will create the directory, but only if it does not already exist. The standard File class manages this for us with the method directory?. The ? on the end just means that it returns a boolean value, true or false.
5. We then change into the directory knowing that is does now exist.