Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何覆盖Ruby+;方法?_Ruby - Fatal编程技术网

如何覆盖Ruby+;方法?

如何覆盖Ruby+;方法?,ruby,Ruby,出于学习目的,我试图重写Ruby+方法,但没有得到所需的输出 class Integer def +(my_num) "Plus method overridden" end end puts 5.+(9) 请让我知道我做错了什么。您似乎使用了rubyFixnum和2.3.3:002>Fixnum.祖先#=>[Fixnum,整数,数字,可比,对象,内核,基本对象]回答得好。为了保持一致性,我建议您将add(other)更改为put add(other),将put 5+9更改为

出于学习目的,我试图重写Ruby+方法,但没有得到所需的输出

class Integer
  def +(my_num)
    "Plus method overridden"
  end
end

puts 5.+(9)

请让我知道我做错了什么。

您似乎使用了ruby<2.4。如果是这样,您希望修补
Fixnum
而不是
Integer
。小心,因为系统本身也使用数字

class Fixnum
  alias_method :add, :+

  def +(other)
    puts 'plus method overridden'
    add(other)
  end
end

puts 5 + 9

看起来您使用的是ruby<2.4。如果是这样,您希望修补
Fixnum
而不是
Integer
。小心,因为系统本身也使用数字

class Fixnum
  alias_method :add, :+

  def +(other)
    puts 'plus method overridden'
    add(other)
  end
end

puts 5 + 9
允许
Integer
具有特定于实现的子类。见第15.2.8.1节第27-33行

看起来您的实现确实有这样的子类。在这种情况下,可以在子类中重写
+
方法

我最好的猜测是,您有一个区分
Fixnum
s和
Bignum
s的实现,我们的
Integer++
Fixnum++
覆盖

顺便说一句,即使你试图做的是工作,它不会被覆盖,它会被覆盖

还要注意的是,如果您试图做的是工作,那么您很可能已经破坏了您的Ruby进程,因为
Integer
s是Ruby中最基本的并且广泛使用。

允许
Integer
具有特定于实现的子类。见第15.2.8.1节第27-33行

看起来您的实现确实有这样的子类。在这种情况下,可以在子类中重写
+
方法

我最好的猜测是,您有一个区分
Fixnum
s和
Bignum
s的实现,我们的
Integer++
Fixnum++
覆盖

顺便说一句,即使你试图做的是工作,它不会被覆盖,它会被覆盖


还要注意的是,如果您试图做的工作是有效的,那么您很可能已经破坏了您的Ruby进程,因为
Integer
s是Ruby中最基本的,并且在Ruby中被广泛使用。

您期望什么?输出为:
Plus方法被覆盖
我得到输出:14您期望什么?输出是:
Plus-method-overrided
我得到的输出是:14值得一提:
2.3.3:001>2.class#=>Fixnum
2.3.3:002>Fixnum.祖先#=>[Fixnum,整数,数字,可比,对象,内核,基本对象]
回答得好。为了保持一致性,我建议您将
add(other)
更改为
put add(other)
,将
put 5+9
更改为
5+9
,并显示所显示的内容。值得一提的是:
2.3.3:001>2.class#=>Fixnum
2.3.3:002>Fixnum[Fixnum,Integer,Numeric,Compariable,Object,Kernel,BasicObject]
回答得不错。为了保持一致性,我建议您将
add(other)
更改为
puts add(other)
,将
puts 5+9
更改为
5+9
并显示导致显示的内容。