[导入]Ruby版的猫抓老鼠

[导入]Ruby版的猫抓老鼠

以前在讲类的时候总喜欢举猫抓老鼠的例子,今天写了一个Ruby版,稍后献上Ruby语法速查
 
class Cat
  def initialize(name, speed)
    @name = name
    @speed = speed
  end
   
  def catch(rat)
    if @speed > rat.speed
      puts @name + " CAN catch " + rat.name
    else
      puts @name + " CAN NOT catch " + rat.name
    end
  end
end
   
class Rat
  attr_reader :speed
  attr_reader :name
  def initialize(name, speed)
    @name = name
    @speed = speed
  end
 end
 
tom = Cat.new('Tom', 60)
jerry = Rat.new('Jerry', 50)
 
tom.catch(jerry)

文章来源: http://blog.sina.com.cn/u/4a5ca02401000760

你可能感兴趣的:([导入]Ruby版的猫抓老鼠)