Wednesday, June 28, 2006

Simple Constructs in Ruby

Today, we shall explore some very simple constructs available in Ruby. The example below (Constructs.rb) illustrates the if else end construct.
# 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 ElsIfEx.rb

Some common conditional operators are: ==, != >=, <=, >, <

Loops like the while are available. Again, the example below illustrates the same.
# Loops
var = 0
while var < 10
puts var.to_s
var += 1
end

I shall talk about another construct the do end when we discuss arrays.

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

7 Comments:

Blogger Robert Gremillion said...

Satish,

Do you want me to post my program as a comment to your post?

The hardest part for me was getting Ruby to get an integer value. At first I was trying to use gets.chomp and then convert it to an integer. I kept getting type errors. Then I found on the web that you could use gets.to_i.

Thanks,

Robert

6:45 PM  
Blogger SatishTalim said...

Robert, you can post your program as a comment to my post

7:20 PM  
Blogger Anish Betawadkar said...

Hi Sir,

I am confused why,

puts 'I can have multiple statements here'
and
puts 'I can not have multiple statements here'

Does the comments imply that I really can not have multiple statements at the second place? I tried and it worked or am I missing something?

7:23 PM  
Blogger SatishTalim said...

Anish, I am sorry the text in the puts statement was confusing. I have changed it. We can have multiple statements both places.

5:13 AM  
Blogger Robert Gremillion said...

Here's the program I ended up with

# accept the year as a integer
tempYear = gets.to_i

# determine if the year entered is a leap year
# and print results
if (tempYear%400 == 0)
puts "#{tempYear} IS a leap year."
elsif (tempYear%4 == 0 && tempYear%100 != 0)
puts "#{tempYear} IS a leap year."
else
puts "#{tempYear} IS NOT a leap year."
end

9:11 AM  
Blogger sandip said...

Hi Satish,
I run a very simple leap year program like Robert, its working fine but i got the message at the end of the result that "leapYear.rb:5: undefined local variable or method `tempyear' for main:Object (NameError)
>Exit code: 1
". Could you please give some comments on the same.

10:24 AM  
Blogger SatishTalim said...

Sandip, send me your code.

12:58 PM  

Post a Comment

Links to this post:

Create a Link

<< Home