Download - Diagrams

Transcript
  • This
  • The Roster class isessentially a hash ofPerson objects, so it needsthe Person class.

    {} is a literal hash.Hashes can also becreated with Hash.new.

    The map method is part of the Enumerablemodule, which all arrays, hashes, ranges,and IO streams use. The map operationreturns a result set consisting of calling thecode block once per member of the inputset. collect is an alias/synonym for map.

    The param = value idiom ina method signature providesa default value for param, whichcan be overridden when themethod is called.

    puts will add a newlineto each line when usedfor file output, just as itdoes for stdout. .

    Regular expressions canbe created with forwardslashes. There's also aRegexp class which canbe instantiated.

    Regular expressions canbe created with forwardslashes. There's also aRegexp class which canbe instantiated.

    The String#scan methodreturns an array of matches(or an array of arrays, if youuse parenthetical sub-matches).

    Parentheses are not requiredin method definitions, but areusually present by convention.

    The @people instance variableis not visible outside the object,and is not wrapped as anattribute.

    The hash[key] = valueidiom actually makes a call to a method whose nameis []= (square brackets equalsign). It's equivalent tohash.[]=(key, value).

    The hash[key] = valueidiom actually makes a call to a method whose nameis []= (square brackets equalsign). It's equivalent tohash.[]=(key, value).

    Ruby has sprintf and printfbuilt in, plus scanf in thestandard library.

    w means: open thisfile in write mode. Othermodes include r (read)and a (append).

    w means: open thisfile in write mode. Othermodes include r (read)and a (append).

    With the code-block(do/end) form of File.oen,Ruby automatically closesthe file handle.

    Parentheses are usually notrequired in method calls, but at timesthey are needed for disambiguation. Except for a few common idioms (likeattr_accessor :name), it's common touse parentheses when calling methods.

    initialize is a special method namein Ruby: the initialize method willautomatically be executed as part ofobject instantion when Roster.new isexecuted

    ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC

  • The constant SIMPLISTIC_EMAIL_REGEXstores a literal regular expression. Thanksto the scope of constants, it will be visiblewhen needed in an instance method.

    Like classes, modules contain methods and constants.Unlike classes, they cannot be instantiated. Rather, theycan be included (or mixed in) to a class (or another module),and/or used for the purpose of extending the functionality of anindividual object. The Person class, for example, mixes inMailableTo via the line include MailableTo.

    Instead of an attr_accessor (setter andgetter methods), MailableTo has anattr_readr method plus a manually-written email= (setter) method. Thisallows for fine-grained checking

    Setting the @email instancevariable will provide a usefulvalue for the email reader accessor.

    The =~ method/operator looks for amatch between a string and a regularexpression. ArgumentError is one of the

    built-in Ruby exception classes.An unhandled exception (such asthe one here) terminates theprogram. The raise method is partof the core language.

    Control-flow keywords like if, unless,while, and until can appear in modifierposition -- that is, at the the of a line.

    Defining a method called email=will allow objects to use syntax like:person.email = [email protected] parser figures out that, evenwith a space before the '=', what'sintendedis a call to the email=method.

    ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC

  • $: is a global variable containingthe current load path, as an array. Adding . to it means that Rubycan find and load program filesin the current workng directory. Allglobal variables begin with '$'. Rubydefines several that govern runtimebehavior (load path, default inputseparator, $VERBOSE warning level,etc.).

    require serves to load a feature, meaning astandard library or third-party extension orlibrary. The loaded file(s) may end in .rbor a system-dependent suffix for compiledextensions, such as .o, .dll, or .bundle.

    Inside a class definition body (butoutside any instance method definition)self refers to the class object itself. Defining a method directly on that classobject results in a class method, which(in this example) can be called asPerson.species.

    The include method serves to mix ina module. Instances of Person will nowbe able to call the instance methodsdefined in the MailableTo module. (Notethat the call to require loaded the file,while include affects the runtime methodlookup behavior of objects.

    The Person class is defined mainly inthe file person.rb. However, it is possibleto reopen an already-defined class, andadd new functionality (instance methods,class methods, constants, mix-ins (viainclude)). It is even possible to reopen coreRuby classes like String and Array andadd to or change them (though it is rarelyadvisable).

    String interpolation is achieved by theuse of the #{...} subexpression insidea double-quoted string. Any expressionor statement can be put inside thebraces, and will be replaced by itscanonical string representation

    The introduce method, defined here inthe re-opened Person class, will functionas an instance method of Person, withexactly the same relation to its class andany instances that call it as the originalinstance methods defined in person.rbhave.

    The value of self here is a Person instance(the instance that called introduce). Morespecifically, the string value, for stringinterpolation purposes, will correspond tothe definition of to_s in person.rb. Rubyobjects have a default string representationbut it's common to define a custom to_s.

    The return keyword is optional here, sincethe method will return the value of thelast (and, in this case, only) expressionevaluated inside it, namely the string HomoSapiens.

    ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC

  • David ([email protected]) is interestedin music, programming, and travel.

    Report after saving and restoring data:David ([email protected])Joe ([email protected])

    First report:David ([email protected])Joe ([email protected])

    Make sure everything's loaded. It's OKto require the same feature twice; therequest is ignored the second time.

    Instantiat Person, and give the new instance an email address and some interests.

    Put the roster save/restore codeto work. Print out the roster, thensave and restore (read) it and printit again. The output from the tworeports, shown in boxes on theleft, is the same.

    Create a second Person, soas to have more than one toadd to a Roster.

    Create a Roster and add boththe people (Person objects) toit.

    This output would all beon a single line in an

    actual console.

    ACM Learning Center -- Ruby Learning PathCopyright 2011, Ruby Power and Light, LLC

    Slide 1Slide 2Slide 3Slide 4Slide 5


Top Related