Ruby Overloading [...] Reducing Array Creation

I wrote a library that extends several Ruby base classes with observation wrappers, mainly using method aliases. However, I ended up in a roadblock with an abbreviated Array instance (for example, @a = [1, 2, 3] ). I cannot find any method that actually called when creating an Array object using shorthand means. This is not an inherited method #[] in the current scope or inherited from any class or module in the ancestor chain. I also overloaded or looked at each method from the #new class to the #new instance in singleton_method #[] in an Array class object based on Ruby C code

 rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1); 

Does anyone know how I can assign a method to be in the method chain of an instance instance of an Array instance?

+4
source share
1 answer

Unfortunately, like many other programming languages ​​on the planet, Ruby does not allow literal overloading. If you need literal overload, you will have to use one of the few programming languages ​​that support it, such as Ioke or Seph .

Here is an example in Ioke:

 [] = method(foo, foo println) [1] ; 1 

And in Seph:

 [] = #(foo, foo println) [1] ; 1 

[Note that this, of course, will lead to the chaos of your system, since, for example, most of the standard Ioke / Seph library is implemented in Ioke / Seph, and they use lists everywhere, so on a production system, you will want to encapsulate this correctly.]

+2
source

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


All Articles