Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, what is the equivalent to an interface in C#?

Tags:

I'm currently trying to learn Ruby and I'm trying to understand more about what it offers in terms of encapsulation and contracts.

In C# a contract can be defined using an interface. A class which implements the interface must fulfil the terms within the contract by providing an implementation for each method and property (and maybe other things) defined. The individual class that implements an interface can do whatever it needs within the scope of the methods defined by the contract, so long as it accepts the same types of arguments and returns the same type of result.

Is there a way to enforce this kind of thing in Ruby?

Thanks

A simple example of what I mean in C#:

interface IConsole {     int MaxControllers {get;}     void PlayGame(IGame game); }  class Xbox360 : IConsole {    public int MaxControllers    {       get { return 4; }    }     public void PlayGame(IGame game)    {        InsertDisc(game);        NavigateToMenuItem();        Click();    } }  class NES : IConsole {     public int MaxControllers     {         get { return 2; }     }     public void PlayGame(IGame game)    {        InsertCartridge(game);        TurnOn();    } } 
like image 732
fletcher Avatar asked Aug 17 '10 18:08

fletcher


People also ask

What is an interface in Ruby?

In particular, in Ruby, the Interface of an object is determined by what it can do, not what class is is, or what module it mixes in. Any object that has a << method can be appended to.

What is abstract class Ruby?

Data Abstraction in Classes: we can use classes to perform data abstraction in ruby. The class allows us to group information and methods using access specifiers (private, protected, public). The Class will determine which information should be visible and which is not.


1 Answers

There are no interfaces in ruby since ruby is a dynamically typed language. Interfaces are basically used to make different classes interchangeable without breaking type safety. Your code can work with every Console as long it behaves like a console which in C# means implements IConsole. "duck typing" is a keyword you can use to catch up with the dynamic languages way of dealing with this kind of problem.

Further you can and should write unit tests to verify the behavior of your code. Every object has a respond_to? method you can use in your assert.

like image 192
Zebi Avatar answered Sep 24 '22 08:09

Zebi