直接上代码: module Action def jump @distance = rand(4) + 2 puts "I jumped forward #{@distance} feet!" end end class Rabbit include Action attr_reader :name def initialize(name) @name = name end end class Cricket include Action attr_reader :name def i…
Ruby学习笔记4: 动态web app的建立 We will first build the Categories page. This page contains topics like Art, Home & Living, and Kids, so our users can browse through categories and find what they like. Each Category in our site will need to store information…
1.类名的定义以大写字母开头,单词首字母大写,不用"_"分隔 2.实例化对象的时候调用new方法,实际上调用的是类里边的initialize方法,是ruby类的初始化方法,功能等同于Java中的构造方法 class Person def initialize(name, gender, age) @name = name @gender = gender @age = age end end 3.可以使用attr_accessor关键字标记实例变量,为其提供读写方法,类似java中的g…
在讨论对象模型时,对类做了初步了解,关于类本身,还有许多知识需要学习. 类定义 Ruby中,可以用class关键字或者Class.new方法来定义一个类,在Ruby中,类定义的同时就是在运行代码,类和方法.块一样,会返回最后一条语句的值,由于类也是一个对象(Class的实例),所以在类定义操作时,类本身就会充当self: result = class MyClass puts self "return value"endputs result 以上语句输出: MyClass…