ruby - 我们可以在 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 没有方法重载。与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
推荐阅读
- html - 在 Spring 中从服务器端渲染 Html/js
- java - Selenium Java Vk 密钥异常
- xamarin - 如何通过传入类型参数来自定义 Xamarin 模板?
- docker - 使用 `docker inspect` 获得的层摘要与从注册表 API 获得的层摘要之间存在差异
- sql - Postgresql 排除已经存在的友谊关系
- vba - Excel VBA宏将符合条件的行复制到另一张纸上的新行
- android - WorkManager - 运行周期性任务
- node.js - Web 进程无法绑定到 $PORT heroku 使用 node.js 部署错误
- e-commerce - 如何启用 2Checkout 以接受全球所有国家/地区的账单/送货地址?
- angular - routerLinkActive 用于多条路由