Recent comments


Syndicate


Follow Me

Twitter Facebook

Ruby Mixins

I've been playing around with Ruby's mixins today and It's really fun. Here's a snippet:

 

module Greeter
  
  def who_am_i?
    "#{self.class.name}"
  end

  def greet
    puts "Hello #{@name}"
  end
  
end

class Student
  
  def initialize(n)
    @name = n
  end
  
  include Greeter
end

class Teacher
  
  def initialize(n)
    @name = n
  end
  
  include Greeter
end

 

Now fire up irb and do this:

 

irb(main):039:0> load 'mixins.rb'
=> true
irb(main):040:0> s = Student.new("Marc")
=> #
irb(main):041:0> t= Teacher.new("Janice")
=> #
irb(main):042:0> s.greet
Hello Marc
=> nil
irb(main):043:0> t.greet
Hello Janice
=> nil
irb(main):044:0>

 

As you can see, you can actually construct the classes body from a module and call its classe's instance variable through the module. cool huh!

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.