Ruby 學習筆記-模組(Module)

為什麼要用模組

class 繼承 class 的方法不就好了?為什麼還要有模組? 因為你只是想要類別裡的其中一個方法,但為了這方法就要繼承這個類別裡的所有方法,這有點過本末倒置。

定義與使用模組

模組的命名規定必須是常數常數必須要是大寫英文字母開頭

  1. include:作用在實體方法

        module Flyable       #定義
                def fly
                    puts "fly"
                end
        end
        class Cat
                include Flyable  #引進
        end
        kitty = Cat.new
        kitty.fly         #使用
        #因為Cat這個類別有引進Flyable這個模組,所以也可以使用fly方法
    
  2. extend:作用在類別方法

        module Flyable       #定義
                    def fly
                        puts "fly"
                    end
        end
        class Cat
            extend Flyable  #在類別裡擴充
        end
        Cat.fly #類別方法
    

模組與類別的差異

  1. 模組沒有繼承的功能,所以不能 module Flyable < SomeModule
  2. 模組不能實體化,所以不能 kitty = Flyable.new

在 Ruby 裡冒號位置的意思

  • 冒號在左 has_many :name 是符號
  • 冒號在右 {name: "lily", age: 18} 是 hash 的 key
  • 冒號在中間,中間有留白 {direction: :up, power: 53} 前面是 key 後面是符號
  • 冒號在中間,中間沒有留白 class User < ActiveRecord::Base User 是繼承 ActiveRecord 模組裡有個叫 Base 的類別
comments powered by Disqus