ruby學習筆記二

來源:互聯網
上載者:User
文章目錄
  • ruby的類
  • 類的繼承
  • 多態
  • 動態語言
  • 編碼

 

ruby的類

首字母大寫,執行個體變數名以@開頭,方法名和參數名用小寫字母或_開頭。

class Person
def initialize(name)
@name = name
@motherland = "china"
end

def talk
puts "my name is " + @name
puts "my motherland is " + @motherland
end
end

talk函數因為沒有參數,所以可以省略括弧。

getter和setter函數可以定義為(以@motherland為例):

    def motherland
return @motherland
end

def motherland = (m)
@motherland = m
end

也可以簡寫為attr_reader:motherland和attr_writer:mother,更簡單的話可以寫為attr_accessor:motherland,這一句話把getter和setter都包括了。

使用這個類的方式如下:

    p = Person.new("meteor")
puts p.motherland
p.motherland = "england"
p.talk
類的繼承

使用<符號表示繼承

    class Student < Person
def talk
puts "students, name: " + @name;
super.talk;
end
end

調用父類的方法用super指明。

所有類的最終父類是Object類,Object類定義了new, initialize...方法。

多態

ruby的函數不能重載。ruby的所有函數相對於C++來說都是virtual的,好像除了C++之外,其它語言都是這樣的。

動態語言

ruby是動態語言,ruby中的類定義之後可以再次定義,重新定義的時候可以往裡增加新的方法,修改原先的方法,增加新的變數等,甚至可以刪除方法。

    class Student
undef talk
end

可以undef的有方法、局部變數、常量,不能undef類、執行個體變數。

另外,remove_method會remove掉當前的方法定義,undef_method會remove掉所有方法的定義。

remove_const可以remove掉常量或者類。

編碼

ruby中,有時將"!"或"?"附於方法名後,"!"表示這個方法具有破壞性,有可能改變傳入的參數,"?"表示這是一個布爾方法,只會返回true或false。

ruby中經常可以省略小括弧

ruby的函數中如果有return語句,會在return處返回,可能會返回一個值,如果最後一行是運算式,那麼即使不寫return,也會自動返回運算式的值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.