Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find "essential" methods to provide an interface of Ruby mixins?

The horribleness of the title of the question is what I'm trying to solve. Example:

in Ruby, Enumerable is an interface in a sense that I can implement something and document it as:

def myfancymethod(please_pass_me_an_Enumerable_here)

but on the other hand, Enumerable is a kind of amplification of the interface that has #each as one of it's methods. If I have a class

class Foo
  def each
    :bar
  end
end

For those unfamiliar with Ruby, if you mixin Enumerable module in a class, you get dozens of methods that only rely on #each method to provide things like #map, #select, etc.

I could say my Foo class is Enumerable-able or Enumerable-compatible or what? What terms describe an answer to "What does it take to be an Enumerable?", "Well you have to have #each"

Similarly, in Ruby

(Array.new.methods - Object.new.methods).size # 111

Does that mean that to fake an Array interface, I have to implement 111 methods? No way, but how to I find out what methods are the "essence" of Array. is it just #[], #[]= and #size? How to make sense of it?

like image 400
ulver Avatar asked May 24 '12 22:05

ulver


2 Answers

I think of the word "contract". Enumerable's contract, for example, is "give me #each and I'll give you these fancy methods".

like image 83
Sergio Tulentsev Avatar answered Nov 06 '22 02:11

Sergio Tulentsev


You might be interested in this feature request, which suggests some improvements to the architecture of the widely used Hash class.

The sad truth is forget about it. At this point Ruby has nothing like this. Enumerable and Comparable are about as close as it gets and their "contract" is merely a matter of documentation.

By the way, I believe #size is the other method that Enumerable can make use of, though it is optional.

like image 23
trans Avatar answered Nov 06 '22 01:11

trans