Академический Документы
Профессиональный Документы
Культура Документы
3 Objectsandmessagepassing
EverythinginRuby,includingstringsandevennil,isanobject. WellseethetechnicalmeaningofthisinSection4.4.2,
butIdontthinkanyoneeverunderstoodobjectsbyreadingthedefinitioninabookyouhavetobuildupyourintuition
forobjectsbyseeinglotsofexamples.
Itseasiertodescribewhatobjectsdo,whichisrespondtomessages. Anobjectlikeastring,forexample,canrespondto
themessagelength,whichreturnsthenumberofcharactersinthestring:
>> "foobar".length
=> 6
Typically,themessagesthatgetpassedtoobjectsaremethods,whicharefunctionsdefinedonthoseobjects.5 Stringsalso
respondtotheempty?method:
>> "foobar".empty?
=> false
>> "".empty?
=> true
Notethequestionmarkattheendoftheempty?method. ThisisaRubyconventionindicatingthatthereturnvalue
isboolean:trueorfalse. Booleansareespeciallyusefulforcontrolflow:
>> s = "foobar"
>> if s.empty?
>> "The string is empty"
>> else
>> "The string is nonempty"
>> end
=> "The string is nonempty"
Toincludemorethanoneclause,wecanuseelsif(else+if):
>> if s.nil?
>> "The variable is nil"
>> elsif s.empty?
>> "The string is empty"
>> elsif s.include?("foo")
>> "The string includes 'foo'"
>> end
=> "The string includes 'foo'"
Booleanscanalsobecombinedusingthe&&(and),||(or),and!(not)operators:
>> x = "foo"
=> "foo"
>> y = ""
=> ""
>> puts "Both strings are empty" if x.empty? && y.empty?
=> nil
>> puts "One of the strings is empty" if x.empty? || y.empty?
"One of the strings is empty"
=> nil
>> puts "x is not empty" if !x.empty?
"x is not empty"
=> nil
SinceeverythinginRubyisanobject,itfollowsthatnilisanobject,soittoocanrespondtomethods. Oneexampleis
theto_smethodthatcanconvertvirtuallyanyobjecttoastring:
>> nil.to_s
=> ""
Thiscertainlyappearstobeanemptystring,aswecanverifybychainingthemessageswepasstonil:
>> nil.empty?
Weseeherethatthenilobjectdoesntitselfrespondtotheempty?method,butnil.to_sdoes.
Theresaspecialmethodfortestingfornilness,whichyoumightbeabletoguess:
>> "foo".nil?
=> false
>> "".nil?
=> false
>> nil.nil?
=> true
Thecode
puts "x is not empty" if !x.empty?
alsoshowsanalternateuseoftheifkeyword:Rubyallowsyoutowriteastatementthatisevaluatedonlyifthe
statementfollowingifistrue. Theresacomplementaryunlesskeywordthatworksthesameway:
>> string = "foobar"
>> puts "The string '#{string}' is nonempty." unless string.empty?
The string 'foobar' is nonempty.
=> nil
Itsworthnotingthatthenilobjectisspecial,inthatitistheonlyRubyobjectthatisfalseinabooleancontext,apart
fromfalseitself. Wecanseethisusing!!(readbangbang),whichnegatesanobjecttwice,therebycoercingittoits
booleanvalue:
>> !!nil
=> false
Inparticular,allotherRubyobjectsaretrue,even0:
>> !!0
=> true
Exercises
1.Whatisthelengthofthestringracecar?
2.Confirmusingthereversemethodthatthestringinthepreviousexerciseisthesamewhenitslettersarereversed.
3.Assignthestringracecartothevariables. Confirmusingthecomparisonoperator==thatsands.reverseare
equal.
4.WhatistheresultofrunningthecodeshowninListing4.9? Howdoesitchangeifyoureassignthevariablestothe
stringonomatopoeia? Hint:Useuparrowtoretrieveandeditpreviouscommands
Listing4.9: Asimplepalindrometest.
>> puts "It's a palindrome!" if s == s.reverse