可以检索单个类附加到的实例的值吗?

时间:2016-04-13 22:04:25

标签: ruby-on-rails ruby

以下是单例类的示例:

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

是否可以在post中回顾def post.some_method

1 个答案:

答案 0 :(得分: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