类
class Person
def self.say_hello
puts 'hello world'
end
end
#p = Person.new
#p.say_hello
Person.say_hello 类方法
扩充一个类的功能 将类重新写一次,添加新的功能
class Person
def self.say_hello
puts 'hello world'
end
end
class Person
def walk
puts 'I can walk'
end
end
p = Person.new
p.walk
模块
module是不能被实例化的,所以下面定义的sqrt方法无法调用,只能添加self
module MyMath
PI = 3.1415
def sqrt(num)
Math.sqrt(num)
end
end
```ruby
class Point
def initialize(x, y)
#@x 实例变量
# @@x 类变量
# $x 全局变量
# x 局部变量
@x, @y = x, y
end
end
p = Point.new(1,2)
p.x # 这样会出错,需要通过getter,setter来获取:attr_getter,attr_setter,attr_accessor
self
class Point
attr_accessor : x, :y
def initialize(x, y)
@x, @y = x, y
end
def first_quadrant?
x > 0 && y > 0 # 等同于self.x或者@a
# 但如果赋值则需要self.x=3,否则ruby不知道是局部变量还是实例变量
end
def self.second_quadrant?(x, y) # 定义类方法,self指class,如果在first_quadrant方法内使用self,指实例,在second_quadrant方法内指类
x < 0 && y > 0
end
class <<self
def foo # 赞同于self.foo
end
def bar
end
end
end
p = Point.new(1, 2)
puts p.y
类变量
class Person
@@age = 1
GENDRE = 'male'
def talk
p 'talk'
end
end
p1 = Person.new
p p1.age #这样是获取不到的
需要作下面的修改
class Person
@@age = 1
GENDRE = 'male'
def talk
p 'talk'
end
def get_age
@@age
end
end
p1 = Person.new
p p1.get_age
#而对于GENDER 则可以通过Person::GENDER来获取
module 是不能被实例化的
puts MyMath::PI p MyMath::sqrt(2) # 报错
而要使用module中的实例方法,则可以通过将module**混入类中(mixin)**实现
```ruby
module Skill
def talk
p "I can talk"
end
end
class Student
include Skill
def walk
p "i can walk"
end
end
s = Student.new
s.talk
s.walk