Ruby 中的方法重写

发布于 2024-12-10 18:11:16 字数 335 浏览 1 评论 0原文

我的代码如下所示:

module A
    def b(a)
      a+1
    end
end
class B
   include A
end

我想在 B 类中编写一个类似如下的方法

class B
   def b(a)
      if a==2     # are you sure? same result as the old method
         3
      else
         A.b(a)
      end
   end
end

我该如何在 Ruby 中执行此操作?

I have code that looks like this:

module A
    def b(a)
      a+1
    end
end
class B
   include A
end

I would like to write a method in the class B that looks sort of like this

class B
   def b(a)
      if a==2     # are you sure? same result as the old method
         3
      else
         A.b(a)
      end
   end
end

How do I go about doing this in Ruby?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玩心态 2024-12-17 18:11:16

您需要 super 函数,它调用该函数的“先前”定义:

module A
  def b(a)
    p 'A.b'
  end
end

class B
  include A

  def b(a)
    if a == 2
      p 'B.b'
    else
      super(a) # Or even just `super`
    end
  end
end

b = B.new
b.b(2) # "B.b"
b.b(5) # "A.b"

You want the super function, which invokes the 'previous' definition of the function:

module A
  def b(a)
    p 'A.b'
  end
end

class B
  include A

  def b(a)
    if a == 2
      p 'B.b'
    else
      super(a) # Or even just `super`
    end
  end
end

b = B.new
b.b(2) # "B.b"
b.b(5) # "A.b"
—━☆沉默づ 2024-12-17 18:11:16
class B
  alias old_b b  # one way to memorize the old method b , using super below is also possible

  def b(a)
    if a==2
        '3'     # returning a string here, so you can see that it works
    else
      old_b(a)   # or call super here
    end
  end
end



ruby-1.9.2-p0 >   x = B.new
 => #<B:0x00000001029c88> 
ruby-1.9.2-p0 > 
ruby-1.9.2-p0 >   x.b(1) 
 => 2 
ruby-1.9.2-p0 > x.b(2)
 => "3"
ruby-1.9.2-p0 > x.b(3)
 => 4 
class B
  alias old_b b  # one way to memorize the old method b , using super below is also possible

  def b(a)
    if a==2
        '3'     # returning a string here, so you can see that it works
    else
      old_b(a)   # or call super here
    end
  end
end



ruby-1.9.2-p0 >   x = B.new
 => #<B:0x00000001029c88> 
ruby-1.9.2-p0 > 
ruby-1.9.2-p0 >   x.b(1) 
 => 2 
ruby-1.9.2-p0 > x.b(2)
 => "3"
ruby-1.9.2-p0 > x.b(3)
 => 4 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文