Simple Constructs
In Ruby, nil and false evaluate to false, everything else (including true, 0) means true. In Ruby, nil is an actual object. You can call methods on nil, just like any other object. You can add methods to nil, just like any other object.
Let's explore some very simple constructs available in Ruby. The example below p014constructs.rb illustrates the if else end construct. By the Ruby convention, if and while do not require parenthesis.
| # if else end var = 5 if var > 4 puts "Variable is greater than 4" puts "I can have multiple statements here" if var == 5 puts "Nested if else possible" else puts "Too cool" end else puts "Variable is not greater than 5" puts "I can have multiple statements here" end |
An example of using elsif is there in the program p015elsifex.rb as shown below:
| # elseif example # Original example puts "Hello, what\'s your name?" STDOUT.flush name = gets.chomp puts 'Hello, ' + name + '.' if name == 'Satish' puts 'What a nice name!!' else if name == 'Sunil' puts 'Another nice name!' end end # Modified example with elseif puts "Hello, what\'s your name?" STDOUT.flush name = gets.chomp puts 'Hello, ' + name + '.' if name == 'Satish' puts 'What a nice name!!' elsif name == 'Sunil' puts 'Another nice name!' end # Further modified puts "Hello, what\'s your name?" STDOUT.flush name = gets.chomp puts 'Hello, ' + name + '.' # || is the logical or operator if name == 'Satish' || name == 'Sunil' puts 'What a nice name!!' end |
Some common conditional operators are: ==, != >=, <=, >, <
Loops like the while loop are available. Again, the example below illustrates the same.
| # Loops var = 0 while var < 10 puts var.to_s var += 1 end |
Assignment:
- Write a Ruby program (p016leapyear.rb) that asks for a year and then displays to the user whether the year entered by him/her is a leap year or not.
- Write a method leap_year. Accept a year value from the user, check whether it's a leap year and then display the number of minutes in that year - program p017leapyearmtd.rb.
Case Expressions This form is fairly close to a series of if statements: it lets you list a series of conditions and execute a statement corresponding to the first one that's true. For example, leap years must be divisible by 400, or divisible by 4 and not by 100. Also, remember that case returns the value of the last expression executed.
year = 2000 leap = case when year % 400 == 0: true when year % 100 == 0: false else year % 4 == 0 end puts leap # output is: true |