zoukankan      html  css  js  c++  java
  • 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  
    "
     4     end
     5 end
     6 
     7 module Flyable    ··        #可飞行的
     8     def fly            #飞行
     9         print "I can fly", "
    "
    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                         
  • 相关阅读:
    排序算法(牢记)
    【性能优化】优化笔记之一:图像RGB与YUV转换优化
    wikioi 3027 线段覆盖 2
    浅谈HTTP响应拆分攻击
    HTTP Response Spliting 防范策略研究
    百度地图API使用介绍
    百度地图
    PHP htmlspecialchars() 函数
    CSRF防范策略研究
    SQL手工注入
  • 原文地址:https://www.cnblogs.com/fish-101/p/10310927.html
Copyright © 2011-2022 走看看