Dr Nic

[Trick] Natural language DSL in Ruby

Ever tried to explain DSLs (domain specific languages) to someone, so that they know how wonderful Ruby is, and just run out of useful examples? Try this piece of Street Magic on them…

The effect

See if your unsuspecting friend can figure out what this code will do. If they can, then say, “That’s because you are a domain expert in English. Good for you. Now use Ruby you Java boy.”

>> I.say "I love the Ruby language"
You said, 'I love the Ruby language'

Cool, yes? Yes.

How this trick works

To set this up for your unsuspecting Ruby noob, type the following into your console/irb:

>> class I; def self.say(text); puts "You said, '#{text}'"; end; end
=> nil

Now you have a constant I upon which you can call class methods.

In long hand, this is:

class I
  def self.say(text)
    puts "You said, '#{text}'"
  end
end

Create other pronoun classes, such as You, Everyone, etc and give them methods representing verbs, such as say, said, want_to.

For example,

class You
  def self.cannot(action, target)
    puts "Didn't your mother tell you never say never? Of course you can #{action} #{target}"
  end
end

Which delights us with:

>> You.cannot :learn, "Ruby"
Didn't your mother tell you never say never? Of course you can learn Ruby

“I still don’t know what a DSL is”

That’s unfortunate for you.

Related posts:

  1. Validate and Save your Ruby in TextMate – with secret Rubinus superpowers In some TextMate bundles, if you save a file it...
  2. Future proofing your Ruby code. Ruby 1.9.1 is coming. Bugger. I’m a Ruby monogamist. I use the Ruby...
  3. Unit Testing iPhone apps with Ruby: rbiphonetest Everything to love about Ruby: the concise, powerful language;...
  4. Using Ruby within TextMate snippets and commands I didn’t know you could run Ruby within TextMate snippets....
  5. The explicit Ruby metaclass you know you always wanted When you define a “static” or “class” method on a...

5 Responses to “[Trick] Natural language DSL in Ruby”

  1. Hah, nice one Nic. I’m half way through an article on internal DSLs with Ruby :)
    I like these pronoun classes.

  2. Chris says:

    Oh that is good. A non-programmer friend of mine once said “it looks like poetry” when I showed him a Ruby DSL. There is hope for mankind, yet.

  3. pony shetland…

    ka-ka-sh-ka 631290 Reviews on pony shetland….

  4. economic justice…

    This page contains some info about economic justice…

  5. easy says:

    wt* it is simple but it explainw what I want to know.