2

我想设计一个类如下:

class A

    @@instances ||= []

    attr_reader :path, :name

    def initialize name
       @name = name
       @path = # I don't know how to get the path of instance.
       @@instances << self
    end

    def self.show_all_instances
        puts @@instances.collect {|i| "Name: #{i.name}, Path: #{i.path}"} .join('\n')
    end
end

然后我将在不同的文件夹下创建许多实例。

folder1/foo.rb
A.new 'foo'
folder2/bar.rb
A.new 'bar'
...

我期望结果如下

A.show_all_instances

输出:

   Name: foo, Path: folder1/foo.rb
   Name: bar, Path: folder2/bar.rb

...

那么我怎么知道调用类在哪里,进入路径呢?

对不起,我没有很好地解释我的问题。我想获取创建实例的 ruby​​ 文件路径...

4

2 回答 2

3
#a.rb
def initialize name,path
   @name = name
   @path = path
   @@instances << self
end

#foo.rb
a = A.new 'foo',__FILE__ #or File.expand_path __FILE__
于 2013-06-06T06:16:07.840 回答
0

我不确定“文件夹下的实例”是什么意思。假设它是“创建”实例的文件,文件名始终为“instance_name.rb”,并gem install y_support用于处理对象命名和实例管理的日常琐事,解决方案是:

require 'y_support/name_magic'
class A
  include NameMagic
  attr_reader :path
  def initialize
    @path = File.dirname( File.expand_path __FILE__ )
  end
  def inspect
    "Name: '#{name}', path '#{path}/#{name.to_s.downcase}.rb'"
  end
end

# Now in folder1
Foo = A.new
# and in folder2
Bar = A.new
# Then:
A.instances
#=> [Name: 'Foo', path 'folder1/foo.rb', Name: 'Bar', path 'folder2/bar.rb']
于 2013-06-06T06:21:39.043 回答