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