iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 7
0
自我挑戰組

Ruby and Rails 的二三事系列 第 7

Ruby and Rails 的二三事 - Day07 Ruby 中的 self 到底是?

第一次看到在Ruby 中看到 self 是在介紹
instance method 和 class method 的時候:

class Cat  
  def say #instance method
    puts "I'm instance method"
  end  
  def self.all #class method ,記得加上self
    puts "I'm class method"
  end
end

kitty =  Cat.new#使用kitty 產生實體
kitty.say       # I'm instance method
Cat.all         # I'm class method

從這時候開始,self 就一直在我的腦海中揮之不去,每天每天都在想著:

親愛的 self, 哩道底洗蝦米碗糕?!

身為一名立志成為工程師的自宅警備員,
遇到問題,找谷哥就對了!
跟著關鍵字(ruby api self)所找到回答是:

self
self is the "current object" and the default receiver of messages (method calls)
for which no explicit receiver is specified.
Which object plays the role of self depends on the context.

英文字太多?沒關係,挑重點看就好:

  • the “current object”
  • the default receiver of messages (method calls)

關於current object

從下面的的程式碼可以看到,當我們試著在不同的地方去印出self(呼叫self) 時,
self 會根據他本身所在的位置而有不同的結果:

p "#{self} outside the class Cat" 
# "main outside the class Cat"

class Cat
  p "#{self} inside the class Cat" 
  # "Cat inside the class Cat"
  def self.eat
    p "#{self} inside the self.eat method" 
    # "Cat inside the self.eat method"
  end
end

Cat.eat

再回頭看看原本定義的內容,應該對self稍微有一點感覺了吧?

Which object plays the role of self depends on the context.
(翻譯蒟蒻:self 在上下文之間的位置,會決定 self 所代表的物件)


關於 default receiver

the default receiver of messages (method calls)
for which no explicit receiver is specified
self automatically receives message that don't have an explicit receiver:

  • receiver ,就是呼叫方法的物件本身。
  • message ,被物件呼叫的方法。

稍微看一下簡單的範例:

[*1..10].select{|i| i.odd?}

[*1..10]i,就是 receiver。
selectodd? 就是個別被呼叫的 message

在看個很常見的整數的加法:

#你以為的整數加法:

  1 + 2

#他在ruby裡真正的樣子:

  1.+(2)

Welcome to the world of object orientation


Summary

回頭再來看看API文件中的範例程式碼:

class String
  def upcase_and_reverse
    upcase.reverse
  end
end

puts "abcd".upcase_and_reverse

#會印出  DCBA

In this method definition, the message upcase goes to self,
which is whatever string calls the method.

其中的 “abcd”.upcase_and_reverse,就可以解釋成:
“abcd”這個字串(current object),本身是個 receiver (default receiver),
呼叫(傳送)了upcasereverse 這兩個method(message)。


以上,就是目前我對self的認識,有錯還請指正。
鐵人賽,我們明天再見!

參考資料:
Ruby-doc.org/Object
Understanding self in Ruby
Ruby Basics : The Default Receiver


上一篇
Ruby and Rails 的二三事 - Day06 Class(類別) 和 Module(模組) 的不同
下一篇
Ruby on Rails 的二三事 - Day08 Rails (Routes 和 MVC)
系列文
Ruby and Rails 的二三事19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言