Question

I want to write a tiny DSL in ruby for simple arithmetic. It would look something like this:

whats 1 + 1
=> 2

whats 2 * 2
=> 4

The use case is teaching my child to program. I was showing her basic programming with irb, and when I gave her the keyboard she typed "whats 2 + 2" - possible in ruby?

Was it helpful?

Solution

Actually, it's quite simple:

def whats expr; expr end

whats 1 + 1
# => 2

OTHER TIPS

What you want can’t be done all that elegantly because of Ruby’s operator precedence. In other words, because whats 1 + 1 is the same as whats(1 + 1) (and whats(2)), the whats method has no idea that an operation occurred in its arguments.

You’ll have to override Fixnum#+ (and any other operators) to return some sort of builder object. For example:

MathQuery = Struct.new(:left, :operator, :right)

class Fixnum
  def + other
    MathQuery.new(self, :+, other)
  end
end

Then 1 + 1 would return a MathQuery instance, which whats would receive and know how to handle.

Of course, the problem with this is that you’d need to somehow also make normal math operations still work, since lots of code obviously expects them to. Not quite sure how to pull that off, though. Maybe if everything always coerced with to_int, etc.…

In which case you might be better off writing an actual mini-language and parser using something like Treetop.

Write a method called 'whats', accept any number of arguments, match the operator portion(s), and proceed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top