📜 ⬆️ ⬇️

Open classes in ruby, notes for pythonists

From my own experience I know that open classes in ruby ​​are annoying and cause misunderstanding among pythonists. Well, in fact, what a weird thing is to open the class String and override the size there?


And you can consider the issue on the other hand, try to make out a small example. Everyone knows how in python different types are checked for truth - everything that is empty is false. In ruby, this is not the case; here the lie is nil and false. Sometimes it would be more convenient as in python.

How can this be solved for example in rust, including support for built-in types:
')
trait Existable { fn exist(&self) -> bool; } impl Existable for int { fn exist(&self) -> bool { if *self == 0 { false } else { true } } } fn main () { assert!(5.exist() == true) assert!(0.exist() == false) } 


Imagine that the scheme in python is not the same, and we want to implement it. In python, you cannot define new methods for third-party classes, so you can do something like:

 class Trait(object): def __init__(self): self.registry = {} def impl(self, typ): def reg(func): self.registry[typ] = func return func return reg def __call__(self, arg): return self.registry[arg.__class__](arg) Existable = Trait() @Existable.impl(int) def int_exists(i): return False if i == 0 else True if __name__ == '__main__': assert Existable(0) == False assert Existable(5) == True 

Well, or use any library that is more sensible than a minute sketch.

How in ruby ​​implemented a similar thing?

 class Object # File activesupport/lib/active_support/core_ext/object/blank.rb, line 13 def blank? respond_to?(:empty?) ? empty? : !self end end 


The method `empty?` Is defined on the classes `Array` and` Hash` (at least). Determine in your class and the method `blank?` Will work correctly. That is, here we have a trait in ruby ​​- objects responding to an `empty?` Implement trait checks for emptiness, the same ʻExistable`.

This is the simplest correct example of using open classes in ruby, and there are many other great things from ActiveSupport, one of the parts of Ruby on Rails.

I hope thanks to such a simple example, you now understand that open classes in ruby ​​are not at all evil, but a useful tool that, in direct hands, allows you to implement extensions of the environment gracefully.

If it was not quite clear what I mean - open classes in ruby ​​allow you to define the behavior of any built-in classes, as well as traits in rust and other languages.

PS I do not claim that in python it is impossible to implement a similar mechanism - I even gave a simple example in the article itself. Once again, this is about the proper use of open classes in ruby, and not about the advantages of any language over another.

Source: https://habr.com/ru/post/214191/


All Articles