定义类实例的默认访问器

问题描述 投票:0回答:1

是否可以为我的类的实例定义默认访问器?

我有一节课:

class Foo
    def initialize(a, b)
        @a = a
        @b = b
    end
end

我想创建这个类的新实例:

foo = Foo.new(:a, :b)
# => #<Foo:0x00007f9e04c7b240 @a=:a, @b=:b>

创建一个新数组会返回一个实际值:

arr = Array.new(2, :bar)
# => [:bar, :bar]

如何设置我自己的类实例的默认访问器,以便当我调用foo时,我得到的是真值而不是#<Foo:0x00007f9e04c7b240 @a=:a, @b=:b>

ruby
1个回答
2
投票

当您在IRB控制台上看到输出时,它所做的就是在对象上调用inspect。所以,你需要做的就是(比如Array),为你的自定义对象定义一个inspect方法:

class Foo
  def initialize(a, b)
    @a = a
    @b = b
  end

  def inspect
    %["Real value" for Foo with #{@a} and #{@b}]
  end
end
foo = Foo.new(:a, :b) # => "Real value" for Foo with a and b

你默认看到的只是Object#inspect的实现,所以如果你真的想要,你可以覆盖所有对象(没有自定义实现):

class Object
  def inspect
    "Custom Inspection of #{self.class.name}"
  end
end

# Foo2 is the same as Foo just without the `inspect` method)
foo_2 = Foo2.new(:a, :b) # => Custom Inspection of Foo2

我会避免为Object#inspect这样做,因为人们已经习惯并期望看到默认格式并且改变事情可能会让他们失望。

© www.soinside.com 2019 - 2024. All rights reserved.