Ruby Programming/Writing methods

← Data types | Classes and objects →

定義方法

编辑

方法是用def保留字開頭定義,以end保留字結束定義。Some programmers find the Methods defined in Ruby very similar to those in Python.

   def myMethod
   end

定義一個方法並且帶有參數,你可以將區域變數放入方法名稱後面的小括號內。變數範圍則是在該方法內部而已。

   def myMethod(msg)
       puts msg
   end

如果有多個參數,則用逗號分隔每個參數。

   def myMethod(msg, person)
        puts "Hi, my name is " + person + " some information about myself is " + msg
   end

任何物件都能傳入方法內。

   def myMethod(myObject)
       if(myObject.is_a?(Integer))
             puts "Your Object is an Integer"
       end
       #檢查如果它是被我們建立的一個物件
       #在下一個章節會講到如何定義物件
       if(myObject.is_a?(MyObject))
             puts "Your Object is a MyObject"
       end
   end

return保留字可以把你要回傳的值給傳回呼叫者。

   def myMethod
       return "Hello"
   end

一些基礎的運算子也能夠透過def保留字重新定義其意義(運算子多載, override)。

   def ==(oVal)
       if oVal.is_a?(Integer)
           #@value is  a variable defined in the class where this method is defined
           #This will be covered in a later section when dealing with Classes
           if(oVal == @value)
               return true
           else
               return false
           end
       end
   end