Skip to content

Tag: method_missing

Ruby: A Simple Example of Meta Programming

A really cool piece of code I read today in the book Ruby on Rails: Up and Running.

class Talker
  def method_missing(method)
     if method.to_s =~ /say_/
       puts $'
     end
  end
end

t = Talker.new

t.say_hello
t.say_something
t.say_goodbye

And running

$ ruby Talker.rb
hello
something
goodbye

But why do that when we have parameters? Because you can do some methods really dynamic with a clear semantic, just looking for them you know are they are doing.