在 Ruby 中,'new' 和 'initialize' 之间的关系是什么?初始化时如何返回nil? [英] In Ruby, what's the relationship between 'new' and 'initialize'? How to return nil while initializing?
问题描述
我想要的是:
obj = Foo.new(0) # => nil or false
这不起作用:
class Foo
def initialize(val)
return nil if val == 0
end
end
我知道在 C/C++/Java/C# 中,我们不能在构造函数中返回值.
I know in C/C++/Java/C#, we cant return a value in a constructor.
但我想知道在 Ruby 中是否可行.
But I'm wondering whether it is possible in Ruby.
推荐答案
在 Ruby 中,'
new
' 和 'initialize
' 之间的关系是什么?
In Ruby, what's the relationship between '
new
' and 'initialize
'?
new
通常调用 initialize
.new
的默认实现类似于:
new
typically calls initialize
. The default implementation of new
is something like:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
# actually, this is obj.send(:initialize, …) because initialize is private
obj
end
end
当然,您可以覆盖它以执行任何您想做的事情.
But you can, of course, override it to do anything you want.
初始化时如何返回nil?
How to return nil while initializing?
我想要的是:
obj = Foo.new(0) # => nil or false
这不起作用:
class Foo
def initialize(val)
return nil if val == 0
end
end
我知道在 C/C++/Java/C# 中,我们不能在构造函数中返回值.
I know in C/C++/Java/C#, we cant return a value in a constructor.
但我想知道在 Ruby 中是否可行.
But I'm wondering whether it is possible in Ruby.
Ruby 中没有构造函数这样的东西.在 Ruby 中,只有方法,它们可以返回值.
There is no such thing as a constructor in Ruby. In Ruby, there are only methods, and they can return values.
您所看到的问题只是您想更改一个方法的返回值,但您覆盖了另一个方法.如果你想改变方法bar
的返回值,你应该覆盖bar
,而不是其他方法.
The problem you are seeing is simply that you want to change the return value of one method but you are overriding a different method. If you want to change the return value of method bar
, you should override bar
, not some other method.
如果你想改变Foo::new
的行为,那么你应该改变Foo::new
:
If you want to change the behavior of Foo::new
, then you should change Foo::new
:
class Foo
def self.new(val)
return nil if val.zero?
super
end
end
但是请注意,这是一个非常糟糕的主意,因为它违反了 new
的约定,即返回一个完全初始化的、功能齐全的班级.
Note, however, that this is a really bad idea, since it violates the contract of new
, which is to return a fully initialized, fully functioning instance of the class.
这篇关于在 Ruby 中,'new' 和 'initialize' 之间的关系是什么?初始化时如何返回nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!