首页 > 解决方案 > 我们可以在 Ruby 中一次调用普通构造函数和参数化构造函数吗?

问题描述

我试过这样。的文件名ClassA是instanceAndClassMethods

class ClassA

    def initialize #constructor 
        puts "This is my constructor" 
    end

    def initialize(a,b)
        c=a-b
        puts c
    end
end

从我在上面的其他类中调用的其他类,因为它们都在同一个文件夹中,例如:

require './instanceAndClassMethods' #filename不应包含空格

obj = ClassA.new #constructor创建对象时自动调用

obj=ClassA.new(33,33)

当我从命令提示符运行时,我得到:

Traceback (most recent call last):
        2: from callMeth.rb:4:in `<main>'
        1: from callMeth.rb:4:in `new'
C:/Users/vkuma102/Desktop/Ruby Learning/instanceAndClassMethods.rb:7:in `initial
ize': wrong number of arguments (given 0, expected 2) (ArgumentError)

如果是这种情况,那么很难正确,而我们可以在 Java 中调用普通构造函数和带参数的构造函数

标签: ruby

解决方案


不,Ruby 没有方法重载。与Java 或Crystal 不同,每个类只能获得一个同名方法。你的第二个def是覆盖第一个。这就像写作foo = 7; foo = 19-7无法再从foo.

如果你想区分不同的参数列表,你需要自己做。幸运的是,与 Java 不同,Ruby 具有可选参数(即具有默认值的参数):

class ClassA
  def initialize(a=nil, b=nil)
    if a && b
      c = a - b
      puts c
    else
      puts "This is my constructor" 
    end
  end
end

推荐阅读