9

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?

ulver
  • 1,521
  • 16
  • 29

2 Answers2

5

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

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • Is there a catalog somewhere of common/existing "Contracts"? I never seen anything like that in Ruby world. I can seen now that in Java this tracking is unnecessary cause you just publish a class used like "new Enumerable(Eachable source)" or do inheritance. – ulver May 25 '12 at 00:07
  • Also, "Design by Contract" is great, but it goes into the whole science of pre/post conditions/invariants etc. I'm just interested in sets of "essential" interfaces. – ulver May 25 '12 at 00:25
4

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.

Dr1Ku
  • 2,875
  • 3
  • 47
  • 56
trans
  • 1,411
  • 1
  • 13
  • 13