On May 29, 9:21 am, Leslie Viljoen <leslievilj...@gmail.com> wrote:
> Hi people
>
> I want to make a library which can extend the String class. I don't want to
> keep putting the class String; def blah; end; end; at the top of all my
> files, I just want to require 'StringExt'
>
> This doesn't work, after I have 'require'd it into my file:
>
> class String
> def to_hex
> unpack("C*").map{|b| b.to_s(16)}.join(" ")
> end
> end
>
> So I tried this:
>
> module StringExt
> def to_hex
> unpack("C*").map{|b| b.to_s(16)}.join(" ")
> end
> end
> ----
> then in my file I put: require 'StringExt'; String.extend StringExt
> .but that didn't work.
>
> Then I tried:
> s = "sdfdsfsdfsdF"
> s.extend StringExt
> s.to_hex
>
> ..but that didn't work.
>
> In the Pragmatic Programmer there's an example, but the module is
> defined in the same file as where it's used - and only the s.extend...
> version then works.
>
> I really want String.extend, to change all strings. How do a 'require'
> a file that then changes the String class?
>
> Les
It sounds like what you want is include, not extend. If your goal is
to add instance methods to all String objects, you can define your
methods in StringExt, and then:
class String
include StringExt
end
In the online first edition of the Pickaxe:
include:
http://whytheluckystiff.net/ruby/pic...lasses.html#UC
extend:
http://whytheluckystiff.net/ruby/pic...lasses.html#UD
HTH,
Chris