在自定义Ruby类中,如何定义实例的默认表示?

时间:2022-02-03 08:34:46

I want an instance of my custom class to have the same methods and behavior as its superclass unless a specific method is invoked on it that returns something (like next, which returns the next Numeric in the sequence). It should act in this case like a String.

我希望我的自定义类的实例具有与其超类相同的方法和行为,除非在其上调用返回某些内容的特定方法(如next,它返回序列中的下一个Numeric)。它应该像String一样在这种情况下起作用。

class MyNumber < Numeric
  ...
end

val = MyNumber.new(1)
# acts like a regular Numeric

val.next
#=> 2

val
#=> "Hello 2!"

puts "Hey #{val}"
#=> "Hey Hello 2!"

In the situation above, I guess I would just redefine to_s.

在上面的情况中,我想我会重新定义to_s。

1 个解决方案

#1


1  

You define the inspect method on that class. For example, if you modify String#inspect as:

您在该类上定义inspect方法。例如,如果将String#inspect修改为:

class String
  def inspect; self * 2 end
end

then you get:

然后你得到:

"Hello" # => "HelloHello"

I suppose you wanted this:

我想你想要这个:

class MyNumber < Numeric
  def inspect; "Hey #{self}" end
end

Note that interpolation "#{}" uses to_s and not inspect, so this does not cause infinite recursion.

请注意,插值“#{}”使用to_s而不是检查,因此这不会导致无限递归。

#1


1  

You define the inspect method on that class. For example, if you modify String#inspect as:

您在该类上定义inspect方法。例如,如果将String#inspect修改为:

class String
  def inspect; self * 2 end
end

then you get:

然后你得到:

"Hello" # => "HelloHello"

I suppose you wanted this:

我想你想要这个:

class MyNumber < Numeric
  def inspect; "Hey #{self}" end
end

Note that interpolation "#{}" uses to_s and not inspect, so this does not cause infinite recursion.

请注意,插值“#{}”使用to_s而不是检查,因此这不会导致无限递归。