【问题标题】:Ruby: what method is called?Ruby:调用什么方法?
【发布时间】:2011-01-08 09:22:30
【问题描述】:

假设,我有一个 x 的对象 MyClass。当我执行puts x 时,会调用什么方法?我需要用我自己的覆盖它。

我以为是.inspect,但不知何故被覆盖的inspect 没有被调用。

比如我有一个班级Sum

class Sum
  initiazlie a, b
     @x = a + b
  end
end

我想像这样访问结果:

s = Sum.new(3,4)
puts s         #=>    7   How do I do this?
puts 10 + s    #=>   17   or even this...?

【问题讨论】:

    标签: ruby object methods overriding


    【解决方案1】:

    它调用:to_s

    class Sum
      def to_s
        "foobar"
      end
    end
    
    puts Sum.new #=> 'foobar'
    

    或者,如果您愿意,您可以从to_s 调用inspect,这样您的对象就有一致的字符串表示形式。

    class Sum
      def to_s
        inspect
      end
    end
    

    【讨论】:

      【解决方案2】:

      首先,您的 Sum 类无效。定义应该是。

      class Sum
        def initialize(a, b)
           @x = a + b
        end
      end
      

      默认情况下,为获得人类可读表示而调用的方法是检查。在irb试试这个

      $ s = Sum.new(3, 4)
      # => #<Sum:0x10041e7a8 @x=7>
      $ s.inspect
      # => "#<Sum:0x10041e7a8 @x=7>"
      

      但在您的情况下,您使用强制字符串转换的puts 方法。为此,首先使用to_s 方法将Sum 对象转换为字符串。

      $ s = Sum.new(3, 4)
      # => #<Sum:0x10041e7a8 @x=7>
      $ puts s
      # => #<Sum:0x10041e7a8>
      $ puts s.to_s
      # => #<Sum:0x10041e7a8>
      

      还要注意你的最后一个例子属于第三种情况。因为您将 Fixnum + 另一个对象相加,所以结果应该是 Fixnum,并且调用的方法是 to_s,但在 Fixnum 类中定义。

      为了在 Sum 类中使用一个,您需要切换 sum 中的项目并在对象中定义 +

      class Sum
        def initialize(a, b)
           @x = a + b
        end
        def +(other)
           @x + other
        end
        def to_s
          @x.to_s
        end
      end
      
      s = Sum.new(3, 4)
      s + 10
      puts s
      # => 17
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多