Ruby China

Ruby 记录一个 Ruby 有而 Java 没有的问题

haohaodehao · 2022年09月09日 · 最后由 pynix 回复于 2022年09月13日 · 983 次阅读

像这样:

module M
 def method_test
 self.class.say_hi
 end
end
class A
include M
end
class B < A
def self.say_hi
end
end
a = A.new
a.method_test

该问题,在我用同事写的"method_test"方法时会发生,他用起来没问题,因为他一直在用 class B 的实例来调 method_test。很愚蠢,该怎么避免呢?

ruby 需要类型检测吗?谁有招解决该问题

用 Java 也可以写这样的代码啊。

Rei 回复

java 有类型检测的,好像没有"self.class"这种套路,这么会有这个问题?ruby 中的 method 不能保证是黑盒、需要担惊受怕的使用

haohaodehao 回复

Java 有

this.getClass()

顶楼代码本质是程序员写了低效的代码,类型系统不能阻止烂代码。如果感觉没有类型不安全,Ruby 3 新增了可选的类型声明 RBS,还有 Stripe 开发的 Sorbet。

Java 没有 include,的确没有这个问题,单继承语言的优势啊!

Ruby 这边建议用 mixin 混入就别在 mixin 里面写 self.class,手动避免一下问题吧。

module M
 def self.included(base)
 base.extend(ClassMethods)
 end
 module ClassMethods
 def say_hi
 p "This is the default say hi method, overwirte it in the included Class if necessary."
 end 
 end
 def method_test
 self.class.say_hi
 end
end
class A
 include M
end
class B < A
 def self.say_hi
 p "This is the say hi method defined in Class B."
 end
end
b = B.new
b.method_test
a = A.new
a.method_test

code review

太灵活了就这样。 ruby 高级特性我都不敢用。。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号

AltStyle によって変換されたページ (->オリジナル) /