Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Ruby module equivalent to a Java Interface?

Tags:

As I understand it, an interface is Java is intended to enforce a design by laying out methods for classes implementing the interface to fill in. Is this the idea with a Ruby module also? I see that just like with Interfaces in Java, you can't instantiate a module in Ruby.

like image 646
Bryan Locke Avatar asked Feb 22 '09 22:02

Bryan Locke


People also ask

Is there interface in Ruby?

Ruby has Interfaces just like any other language.

What is a Ruby module?

Ruby module is a collection of methods and constants. A module method may be instance method or module method. Instance methods are methods in a class when module is included. Module methods may be called without creating an encapsulating object while instance methods may not.

What is the difference between a class and a module Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

Can a module contain a class Ruby?

A Ruby module can contain classes and other modules, which means you can use it as a namespace.


1 Answers

The short answer is no.

Here's the reasoning, a Java/C# interface defines the method signatures an implementing class will provide at minimum.

Additionally:

  • With ruby modules there is no such contract because of the duck-typing.
  • Modules are just a way to extract out common functionality for easy re-use. The closest relation is C# extension methods, but those aren't an exact match since they exist in a static context.
  • Modules can add state to an existing class.
  • Modules can have static methods
  • Modules can act as namespaces

Example:

module SimpleConversation
  class NamespacedExample
    def poke
      puts "ouch"
    end
  end

  attr_accessor :partner_name
  def converse
    partner_name ||= "Slowpoke"
    speak + "\n#{partner_name}: Yes they are"
  end

  def self.yay
    puts "yay"
  end
end

class Foo
  include SimpleConversation
  attr_accessor :name

  def speak
    name ||= "Speedy"
    "#{name}: tacos are yummy"
  end
end

x = Foo.new
x.name = "Joe"
x.partner_name = "Max"
puts x.speak
puts x.converse

y = SimpleConversation::NamespacedExample.new
y.poke

SimpleConversation.yay
like image 195
segy Avatar answered Oct 12 '22 05:10

segy