2016-04-13 15 views
0

這裏是單例類的一個例子:可能檢索哪個單例類附加到的實例的值?

class MyPost < ActiveRecord::Base 
    def initialize(title) 
    @title = title 
    end 
end 

post = MyPost.new(:title => 'post title') 

def post.some_method 
    #is it possible to retrieve value of `post`? 
    my_post_title = post.title #???. Not working now 
end 

是否有可能重提postdef post.some_method

回答

1

有錯誤:在標題 1.無休止單引號。 2.當你在裏面post那麼你可以直接訪問@title,你不能把它post.title

class MyPost < ActiveRecord::Base 
    def initialize(title) 
    @title = title 
    end 
end 

post = MyPost.new(:title => 'post title') 

def post.some_method 
    my_post_title = @title 
end 

post.some_method 

,或者如果您已經從設置你的attr_accessor爲您title

require 'active_record' 

class MyPost < ActiveRecord::Base 
    attr_accessor :title 
    def initialize(title) 
    @title = title 
    end 
end 

post = MyPost.new(:title => 'post title') 

def post.some_method 
    my_post_title = title 
end 
+0

downvoter可以指定什麼是錯誤的程序? – uday

+0

'title'在調試中返回'nil'。 – user938363

+0

我有兩種方式來做它..請看看哪一個適合你 – uday

2

是的。內的方法,該特殊變量self保持對所述消息的接收器的引用:

class MyPost < ActiveRecord::Base 
    def initialize(title) 
    @title = title 
    end 
end 

post = MyPost.new(title: 'post title') 

def post.some_method 
    my_post_title = title 
end 
+0

這樣的錯誤了。標題不是一個常數或在範圍內未被定義 – uday

+0

如果是這樣的話,那麼OP的問題就沒有意義了。 OP的代碼假定他可以在由變量'post'引用的對象上調用名爲'title'的方法。我的回答只是與OP的問題完全相同的假設。 OP的問題僅僅是關於如何獲得對象的引用,而不是如何定義名爲'title'的方法。我假設OP已經知道如何定義方法。 –

+0

但你有沒有測試過你的代碼? – uday