self.function 遇到 self.class.function

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
765   0  
·
2018/06/19
·
2 mins read


self.function 是個 instance,所以要用的時候,要先有這個 instance,譬如:foo.new;self.class.function 是個 class⋯⋯ 越聽越沒懂?沒關係,把它 puts 出來:

  • put foo.function #=> #<foo:0x000000026bb7f8>; #<XX:0x000000026bb730>
    • 所以是個變數!
  • put foo.function #=> foo; XX 
    • 就是個 class

好啦好啦,我是故意弄煩各位的,以下是標準答案:

class level method:

def self.function
end 

當你要呼叫它時:

如果你的 model 是User,很簡單就可以用 User.method 呼叫他。

最接近的舉例就是 User.all 或是 User.find().

instance level method:

def function
end 

如果你的 model 還是User,就:

u=User.new

u.method 就可以了!

最接近的舉例就是 x.save 或是 x.destroy.

 

其實,在 Ruby 中,沒有 Class level method 這件事,它只是這個 class 的 metaclass instance 而已,不過不重要啦,記住 class method 跟 install method 是不能互換用的就好,搞清楚後,就不會昏了。

對純物件導向語言(Object Oriented)的愛好者而言,Class method 是不好的寫法,因為這種寫法其實很像程序式程式語言(Procedural programming),Class method 比需要使用完整與正確的參數,相對於 instance method,物件本身就能帶有正確的參數,確實必較容易除錯,只是我就是個程序式程式語言的愛好者,雖然我同意 Class method 真的好像比較不好,但是我很愛用,因為簡單乾淨,不過這就是個人風格的問題了,這便文章個位可以參考,是網路名文:Are class methods evil?


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

Categories:
Tags:
Total: 366 words


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.