[Ruby][Class] Ruby 中使用 class

林班尼
3 min readJul 4, 2020

--

方法筆記中 介紹Ruby 的如何定義與使用method 就像是其他程式語言中

實用函數 function,如果今天要實做許多種類別 如移動工具 |動物園|海洋世界等等... 很多種不同的種類 那就得定義與多方法 例如 實做一個動物行為方法 ,就需要更多的判段式去執行如下

def  talk(animal_type,name)   if animal_type == "dog"
puts "#{name} says bark"
elsif animal_type =="bird"
puts "#{name} says chirp!"
end
# 更多的動物需要更多 if elsif
end

所以我們可透過 Ruby 中的類別 class 來實做,透過類別實做一種物種

而此物種擁有各自行為模式 這樣一來 透過class 實現物種中各自的行為(方法)

#class 宣告
#Ruby 類別名稱須以大寫開頭其餘字母小寫
class Dog #dog 是類別名稱
def talk #定義類別方法
puts "Bark!"
end
def move(destination) #定義類別方法
puts "Running to the#{destination}"
end
end

#-----------類別建立一個實體-----------
fido=Dog.new

#-----------類別方法呼叫-----------
fido.talk
fido.move("home")
#class 宣告
#Ruby 類別名稱須以大寫開頭其餘字母小寫
class Dog #dog 是類別名稱
def talk #定義類別方法
puts "Bark!"
end
def move(destination) #定義類別方法
puts "Running to the#{destination}"
end
end

#-----------類別建立一個實體-----------
fido=Dog.new

#-----------類別方法呼叫-----------
fido.talk
fido.move("home")

如何在class 中使用實體變數?

#區域變數  my_variable
#實體變數 @my_variable

class Dog # 類別名稱字首大寫
def make_up_name
@name="may" #設定 初始名稱為 may
end

def talk
puts "#{@name} says Bark!" #使用全域變數
end

end

#-----------類別方法呼叫-----------
may = Dog.new
may.make_up_name
may.talk

「ref」 文中為閱讀深入淺出Ruby 筆記

--

--