Ruby Simplified Part 3: Ruby conditional statements
August 27, 2018 Leave a comment
Let’s look at some conditional statements in Ruby, if-else, case, and unless.
=begin A simple program to test user input, notice that this comment is multiline =end # If-Else statement puts "Please input number..." x = gets # Get user input x = x.chomp # Chop off the '\n' at the end x = x.to_i # convert the string into an integer if (x < 0) puts "user input " + x.to_s + " is negative" # convert integer into string with .to_s elsif (x == 0) puts "user input " + x.to_s + " is zero" else puts "user input " + x.to_s + " is positive" end # The 'if' modifier puts "Writes this line only if x is 1" if x == 1 # Case statement puts "Please input another number..." x = gets.chomp.to_i # Notice how we shorten the operations case when x < 0 puts "user input " + x.to_s + " is negative" when x == 0 puts "user input " + x.to_s + " is zero" when x > 0 puts "user input " + x.to_s + " is positive" end # Unless statement puts "Please input another number..." x = gets.chomp.to_i unless x > 0 # The equivalent of 'unless' is the if(!...) in C# unless x == 0 puts "user input " + x.to_s + " is negative" else puts "user input " + x.to_s + " is zero" end else puts "user input " + x.to_s + " is positive" end # Unless conditional puts "Write this line unless x is 0, meaning, if x is 0 then don’t write this line" unless x == 0 # Anything inside 'BEGIN' is called before the program is run BEGIN { puts "Simple program to test user input." } # Anything inside 'END' is called after the program is run END { puts "All done!" }