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.
Ruby has Interfaces just like any other language.
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? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).
A Ruby module can contain classes and other modules, which means you can use it as a namespace.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With