问题
I've written a library that extends several base Ruby classes with observing wrappers mostly through method aliasing. However, I've hit a roadblock with the Array instantiation shorthand (e.g. @a = [1, 2, 3]
) I can't seem to find any method that's actually called in the creation of an Array object by the shorthand means. It's not an inherited #[]
method in the current scope or inherited from any class or module in the ancestors chain. I've also overloaded or watched every method from the class's #new
to an instance's #initialize
to the singleton_method #[]
on the Array class object based on the Ruby C code
rb_define_singleton_method(rb_cArray, "[]", rb_ary_s_create, -1);
Does anyone know how I can assign a method that would be within the method chain of the shorthand Array instance instantiation?
回答1:
Unfortunately, like pretty much every other programming language on the planet, Ruby does not allow overloading of literals. If you require literal overloading, you will have to use one of the few programming languages which support it, like Ioke or Seph.
Here's an example in Ioke:
[] = method(foo, foo println)
[1]
; 1
And in Seph:
[] = #(foo, foo println)
[1]
; 1
[Note that these will, of course, wreak havoc with your system, since, for example, a large part of the Ioke/Seph standard library is implemented in Ioke/Seph, and they use lists all over the place, so in a production system, you'll want to properly encapsulate this.]
来源:https://stackoverflow.com/questions/8116917/overloading-rubys-array-creation-shorthand