Professional Documents
Culture Documents
3 Modifyingbuiltinclasses
Whileinheritanceisapowerfulidea,inthecaseofpalindromesitmightbeevenmorenaturaltoadd
thepalindrome?methodtotheStringclassitself,sothat(amongotherthings)wecancallpalindrome?onastring
literal,whichwecurrentlycantdo:
>> "level".palindrome?
NoMethodError: undefined method `palindrome?' for "level":String
Amazingly,RubyletsyoudojustthisRubyclassescanbeopenedandmodified,allowingordinarymortalssuchas
ourselvestoaddmethodstothem:
>> class String
>> # Returns true if the string is its own reverse.
>> def palindrome?
>>
self == self.reverse
>> end
>> end
=> nil
>> "deified".palindrome?
=> true
(Idontknowwhichiscooler:thatRubyletsyouaddmethodstobuiltinclasses,orthat"deified"isapalindrome.)
Modifyingbuiltinclassesisapowerfultechnique,butwithgreatpowercomesgreatresponsibility,anditsconsidered
badformtoaddmethodstobuiltinclasseswithouthavingareallygoodreasonfordoingso. Railsdoeshavesomegood
reasonsforexample,inwebapplicationsweoftenwanttopreventvariablesfrombeingblanke.g.,ausersname
shouldbesomethingotherthanspacesandotherwhitespacesoRailsaddsablank?methodtoRuby. SincetheRails
consoleautomaticallyincludestheRailsextensions,wecanseeanexamplehere(thiswontworkinplainirb):
>> "".blank?
=> true
>> "
".empty?
=> false
>> "
".blank?
=> true
>> nil.blank?
=> true
Weseethatastringofspacesisnotempty,butitisblank. Notealsothatnilisblanksincenilisntastring,thisisa
hintthatRailsactuallyaddsblank?toStringsbaseclass,which(aswesawatthebeginningofthissection)
isObjectitself. WellseesomeotherexamplesofRailsadditionstoRubyclassesinSection9.1.
Exercises
1.Verifythatracecarisapalindromeandonomatopoeiaisnot. WhataboutthenameoftheSouthIndianlanguage
Malayalam? Hint:Downcaseitfirst.
2.UsingListing4.16asaguide,addashufflemethodtotheStringclass. Hint:RefertoListing4.12.
3.VerifythatListing4.16worksevenifyouremoveself..
Listing4.16: Skeletonforashufflemethod
attachedtotheStringclass.
>> class String
>> def shuffle
>>
self.?('').?.?
>> end
>> end
>> "foobar".shuffle
=> "borafo"