13 Apr 2009

Q1. Create, test and debug a Ruby program called dognames.rb or catnames.rb...

Q1. Create, test and debug a Ruby program called dognames.rb or catnames.rb to accept 3 names from the keyboard and to display each name on the screen in alphabetical order WITHOUT using a data structure such as a list. Answer:

I have written the dognames.rb ruby program. The diagram-50 shows the screen dump (result) of running dognames.rb in Ruby console.

Diagram-50 - The result of running dognames.rb

The code of dognames.rb is listed below...

#!C:\InstantRails-2.0-win\ruby\bin\ruby
# The Dog Name Program to sort the dogname without using sort method
# assume all inputs of the dog names are not the same

def dognames
# get the three dogs' names
puts "Enter the first dog's name: "
$dog1 = STDIN.gets
puts "Enter the second dog's name: "
$dog2 = STDIN.gets
puts "Enter the third dog's name: "
$dog3 = STDIN.gets

first=""
second=""
third=""

if ($dog1 <=> $dog2)==-1 && ($dog1 <=> $dog3)==-1
first=$dog1
if ($dog2 <=> $dog3)==-1
second=$dog2
third=$dog3
else
second=$dog3
third=$dog2
end
elsif ($dog1 <=> $dog2)==-1 && ($dog1 <=> $dog3)==1
first=$dog3
second=$dog1
third=$dog2
elsif ($dog1 <=> $dog2)==1 && ($dog1 <=> $dog3)==-1
third=$dog3
second=$dog1
first=$dog2
elsif ($dog1 <=> $dog2)==1 && ($dog1 <=> $dog3)==1
third=$dog1
if ($dog2 <=> $dog3)==1
second=$dog2
first=$dog3
else
second=$dog3
first=$dog2
end
end

puts "The order of dogs' names is "
puts
puts first+" "+second+" "+third
end
dognames



No comments:

Post a Comment