rubystringbuilt-in-types

What is the proper way to add a method to a built-in class in ruby?


In exercism.io I have submitted a solution ot the Pangram Problem in Ruby.

To solve the problem, I created a method for the String class called alpha? which determines if a character is alphabetial or not ('a'..'z'). This method is inside a module which I then include in the String class.

Here is my code:

module Str_Plus
  def alpha?
      self[/[a-zA-Z]+/] == self
  end
end

class Pangram
  String.include Str_Plus 
  ...
end

Someone mentioned this is NOT the best way to add functionality to a built-in class.
My question is, What is the proper way?


Solution

  • tenebrousedge there was probably hinting at refinements.

    Or, rather, not patching String at all. More often than not, monkeypatching creates more problems than it solves. What if String already knew alpha? and it did something different?

    For example, future versions of ruby might add String#alpha? that will handle unicode properly

    '新幹線'.alpha? # => true
    

    and your code, as it is, would overwrite this built-in functionality with an inferior version. Now your app is breaking in all kinds of places, because stdlib/rails assumes the new behaviour. Chaos!

    This is to say: avoid monkeypatching whenever possible. And when you can't avoid, use refinements.