inicio mail me! sindicaci;ón

Archive for Ruby

Fixing the Prototype Enumeration Mixin

The following article describes ticket #3592 in the RoR Trac and explains a proposed solution.

Prototypes Enumerable mixin class does not properly respect the mixees internal format. For example the reject and findAll methods, operating on Hashes, return Arrays instead of Hashes.

var a = $H({a:1, b:2, c:1, d:3}); 


var b = a.reject(function(val){ return (val[1]==1) });

=> [['b', 2], ['d', 3]]   // !!! should be hash

var c = b.findAll(function(val){ return (val[0]=='d') });

=> [['b', 2], ['d', 3]]   // !!! should be hash

In Ruby (from which the inspiration for the Enumerable Mixin stems), the reject method does return a hash, not an array, when operating on an hash:

irb(main):001:0> a={:a => 1, :b => 2, :c => 1, :d => 3}  

=> {:b=>2, :c=>1, :a=>1, :d=>3}  

irb(main):002:0> b=a.reject{|k,v| v==1}

=> {:b=>2, :d=>3} 

The patch requires all classes that want to mixin Enumerable to define two more methods similar to _each:
_new, which returns an empty object of that class and
_add, that adds an element. Enumerable mixin thus needs to make no more assumptions about the internal structure of its mixee class.

After the fix the methods return correctly:

=> #
« Previous entries