CSC/ECE 517 Fall 2009/wiki2 4 va: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
mNo edit summary
Line 1: Line 1:
Topic
Example using IF statement:
4 - if-statement considered harmful
 
<pre>
class Vehicle
  def initialize
    puts "I am a vehicle"
  end
end
 
class Car < Vehicle
  def initialize
    super
    puts "I am a passenger car"
  end
end
 
class Truck < Vehicle
  def initialize
    super
    puts "I am a commercial truck"
  end
end
 
class Driver
  puts "Do you have a Car or a Truck?"
  #Expects Car or Truck, case sensitive
  type = gets           
  my_car = eval(type).new
 
  if my_car.class == Car
    puts "I like 87 octane gasoline"
  elsif my_car.class == Truck
    puts "I like diesel"
  end
end
</pre>
 
 
Example using polymorphism:
 
<pre>
class Vehicle
  def initialize
    puts "I am a vehicle"
  end
end
 
class Car < Vehicle
  def initialize
    super
    puts "I am a passenger car"
  end
 
  def get_type_of_fuel
    "I like 87 octane gasoline"
  end
end
 
class Truck < Vehicle
  def initialize
    super
    puts "I am a truck"
  end
 
  def get_type_of_fuel
    "I like diesel"
  end
end
 
class Driver
  puts "Do you have a Car or a Truck?"
  #Expects Car or Truck, case sensitive
  type = gets
  my_car = eval(type).new
  puts my_car.get_type_of_fuel 
end
</pre>

Revision as of 17:47, 8 October 2009

Example using IF statement:

class Vehicle
  def initialize
    puts "I am a vehicle"
  end
end

class Car < Vehicle
  def initialize
    super
    puts "I am a passenger car"
  end
end

class Truck < Vehicle
  def initialize
    super
    puts "I am a commercial truck"
  end 
end

class Driver
  puts "Do you have a Car or a Truck?" 
  #Expects Car or Truck, case sensitive
  type = gets             
  my_car = eval(type).new

  if my_car.class == Car
    puts "I like 87 octane gasoline"
  elsif my_car.class == Truck
    puts "I like diesel"
  end
end


Example using polymorphism:

class Vehicle
  def initialize
    puts "I am a vehicle"
  end
end

class Car < Vehicle
  def initialize
    super
    puts "I am a passenger car"
  end
  
  def get_type_of_fuel
    "I like 87 octane gasoline"
  end
end

class Truck < Vehicle
  def initialize
    super
    puts "I am a truck"
  end
  
  def get_type_of_fuel
    "I like diesel"
  end
end

class Driver
  puts "Do you have a Car or a Truck?" 
  #Expects Car or Truck, case sensitive
  type = gets
  my_car = eval(type).new
  puts my_car.get_type_of_fuel  
end