Ruby循序渐进(一): 类的创建与使用

# Class Demo

class Dog
    def set_name(aName)
        @myname = aName
    end
    
    def get_name
         return @myname
    end
    
    def talk
        puts "Woo! I'm " + get_name
    end
end


class Cat  
    def set_name(aName)
        @myname = aName
    end
    
    def get_name
         return @myname
    end
    
    def talk
        puts "Miao! I'm " + get_name
    end
end

# Create instances of the Dog and Cat classes
dog1 = Dog.new
dog2 = Dog.new
cat1 = Cat.new
cat2 = Cat.new
anonymous_dog = Dog.new

# set name
dog1.set_name('Tom')
dog2.set_name('Jack')
cat1.set_name('Mary')
cat2.set_name('Rose')


# --- Get their names and display them
#
 Dogs
puts(dog1.get_name)
puts(dog2.get_name)
# hmmm, but what happens here if the dog has no name?
puts(anonymous_dog.get_name)

# Cats
puts(cat1.get_name)
puts(cat2.get_name)

# Ask them to talk
puts(dog1.talk)
puts(dog2.talk)
puts(cat1.talk)
puts(cat2.talk)
posted @ 2012-06-12 17:37  Master HaKu  阅读(163)  评论(0编辑  收藏  举报