Why_refine
module StrRows
refine String do
def lines = ( scan("\n").size )
end
end
class Xstr < String
using StrRows
end
some_text = <<-MUSK
Strive to greater heights,
For a future brighter than the past,
Waking up each morning inspired,
To learn new secrets of the Universe!
MUSK
xstr = Xstr.new(some_text)
p some_text.lines
# =>[
# "Strive to greater heights,\n",
# "For a future brighter than the past,\n",
# "Waking up each morning inspired,\n",
# "To learn new secrets of the Universe!\n"
# ]
p xstr.lines # => 4
Suppose you want a fancy new String-method that returns the number of lines in a text. Unbeknownst to you.. String already have a method named ’lines’. It splits a line on new-line and returns an Array.
But you are careful and create a module where you refine the String-class. You even create a class for your Strings.
xstr is NOT a String.. it is an Xstr, and as such it has a refined method called ’lines’ that returns the number of new-line characters in the string.
So.. xstr.lines
and some_text.lines
are not calling the same method.
(In this example the module is superfluous since you could add the method to the class directly. You have to imagine the class having more methods where some will use the String#lines and some the Xstr#lines.)