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.
Some common conditional operators are: ==, != >=, <=, >, <
Loops like the while are available. Again, the example below illustrates the same.
I shall talk about another construct the do end when we discuss arrays.
Technorati Tags: Simple Constructs in Ruby
Blogs linking to this article
# if else endAn example of using elsif is there in the program ElsIfEx.rb
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
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: Simple Constructs in Ruby
Blogs linking to this article





7 Comments:
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
Robert, you can post your program as a comment to my post
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?
Anish, I am sorry the text in the puts statement was confusing. I have changed it. We can have multiple statements both places.
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
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.
Sandip, send me your code.
Post a Comment
Links to this post:
Create a Link
<< Home