Re: [問題] 相同的instance和class method

看板Ruby作者 (godfat 真常)時間15年前 (2010/05/11 18:04), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/4 (看更多)
※ 引述《ihower (好2ˇ)》之銘言: : 是指 instance method 跟 class method 一樣嗎? XD : def price : self.class.price : end : def self.price : ... : end [...] : 推 godfat:不建議這樣設計,很混淆 05/10 22 : 推 bypang:godfat大大有何建議嗎?一個是virtual attributes 05/11 12 : 推 bypang:一個是class method,可是都有相同的code 05/11 12 : → godfat:看起來不像是 virtual attribute,而是class method wrapper 05/11 15 我在 facebooker 裡面看到不少類似的用法,這讓我感到很混淆, 因為我會搞不清楚當我看到 Item.price 和 Item.new.price 之間的差別是什麼? 翻了 source code 之後才發現其實根本一樣。 我覺得所謂 instance method, 就是為了存取 instance variable. 覺得打 item.price 或是 Item.price 或是 item.class.price 應該也沒省幾個字吧? 但是兩者混用時,乍看之下還真不知道有什麼差別。 我會假設 item.price 會根據某個東西,比方說,某些 item 有打折, 而 Item.price 則是某種定價,不會根據不同 item 而有所改變的。 這邊只是隨便舉例,我想說的是,就打 Item.price 並沒有那麼難... 多個 instance method 去呼叫 class method 沒什麼必要。 -- #!/usr/bin/env ruby [露比] /Programming (Kn|N)ight/ 看板《Ruby》 # if a dog nailed extra legs that http://www.ptt.cc/bbs/Ruby/index.html # walks like an octopus, and Welcome ~Ruby@ptt~ # talks like an octopus, then ◢█◣ http://www.ruby-lang.org/ # we are happy to treat it as http://www.ruby-doc.org/ # if it were an octopus. http://www.rubyforge.org/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.168.130.55

05/13 05:21, , 1F
我也不喜歡這種作法... 有啥特別適合的例子嗎XD?
05/13 05:21, 1F
文章代碼(AID): #1BwIkUjL (Ruby)
文章代碼(AID): #1BwIkUjL (Ruby)