String Difference in Ruby

class String

  def -(other)
    self.index(other) == 0 ? self[other.size..self.size] : nil
  end
end

This snippet gives the Ruby String class a minus operator. Which works like

> 'abcde' - 'abc'
=> "de"
> '    ' - '  '
=> "  "

> 'abc' - 'de'
=> nil

Meh.

blog comments powered by Disqus