ruby基础知识之 class&module

以下分别介绍了class方法和module方法,还有最简单的def方法。

其中module和class的区别下面会说,这里首先声明,def定义的方法,需要定义对象后才能调用,而class和module都能随意进入。

class方法

ruby里的方法分为:类方法和实例方法

类方法:通过类名直接调用的方法 

可以写的形式一般是3类:

第一种:

class Fo
  def self.bar
    p "aa"
  end
end

第二种:

class Foo
  class << self

    def bar 
       p "bb"

    end
  end
end

第三种:
class Fooo; end
  def Fooo.bar
  end

 

调用的时候:直接Foo.bar 这样调用即可。

 

实例方法:通过对象调用的方法

可以写成的形式也有3种:

 

第一种:

class Foo
  def baz
    p "mm"
  end
end

 

第二种:

class Foo
  attr accessor :baz
  end
foo = Foo.new
foo.baz = "instance method"

第三种:这种方法只针对foo这一个对象有效,称为单例方法,函数范围很小
class Foo; end
foo = Foo.new
def foo.baz
  p "instance method"
end

调用实例方法的时候,一定要先new一个对象出来

 

 

module(模块)方法

提前声明:module方法是ruby语言特有的,它是一个命名空间,避免定义了相同名称的函数或变量导致的冲突。

module也分为module实例方法和module类方法,它的写法其实与类方法是一毛一样的。比如:

 

上面这段代码就是一个模块类方法,特点是在定义方法和调用方法的时候都在前面加上了所在module的名字,这样定义的函数就叫module method 。

在定义方法名称的时候,我们不加module name,这样定义出来的方法就叫模块实例方法(module instance method),这种方法就是实例方法,只能被mixin到某个class中被引用。

 

module与class的区别:

1、module不能实例化,即module为实例方法的module时,它不能被自己引用,需要利用include方法引用到class中;

2、module不能继承,而class可以

常量定义:凡是首字母大写的,都是常量,包括class和module都是,常量在调用的时候用::

调用规则:

类调用用::或者.

实例调用只能用.

所以为了区分,一般类调用我们都用::

 

 

下面说一下class对module的调用:

 1 module Mammal        # 哺乳动物
 2     def suckle        # 哺乳
 3         print "I can suckle my baby  \n"
 4     end
 5 end
 6 
 7 module Flyable    ··        #可飞行的
 8     def fly            #飞行
 9         print "I can fly", "\n"
10     end
11 end
12 
13 class Chiropter                    #蝙蝠
14     include Mammal        #蝙蝠是哺乳动物
15     include Flyable        #蝙蝠可以飞行
16 end
17 
18 achiropter = Chiropter.new
19 achiropter.suckle
20 achiropter.fly
21                         

 

posted on 2019-01-23 19:33  101欢欢鱼  阅读(940)  评论(0编辑  收藏  举报

导航