diagrams

5
This << infix operator is actually a method of the Array class. This expression is “syntactic sugar” for @interests.<<(interest) (the << method called with one argument. Many infix operators in Ruby are actually methods -- even arithmetic ones. (2 + 3 is really 2.+(3), for example.) @name and @interests are instance variables. They represent internal, per-object state. In the case of @name, the instance variable also serves as the cache for an attribute accessor, declared above.). @interests is the same instance variable that was previously set to an empty array. attr_accessor declares one or more “attributes”. Attributes are implemented as simple getter/setter wrapper methods around instance variables. Method names can end with a question mark. The use of such methods as Booleans is purely conventional and is not enforced at the language level. The :name notation indicates a symbol, a built-in class often used for short, character-based data. Note the spelling of elsif. A method's return value either is indicated by an explicit return statement, or defaults to the value of the last expression evaluated in the method's execution. return "" would also work here. 0..-2 is a range object. Here, it serves to index the array, from the first (0'th) element to the second-to-last element (indexed as -2). join'ing an array returns a string, with the array elements in string form connected by the (optional) separator string. Strings can be “added” together with the + operator (which is really a method.) If a line ends inconclusively (e.g., with a plus-sign), Ruby will assume that the statement continues on the next line. Indentation by two spaces (not tabs, and exactly two) is the traditional and nearly-universal Ruby convention. Person, is a constant, as indicated by its starting with an uppercase letter Classes (and modules) can be stored in local variables but are typically declared and named with constants. self is the “current” or “default” object. Which object is self depends on context. In a method, self is the object on which the method was called. Here, a Person object calls its own name accessor method. to_s defines the standard/default string representation for a class. Ruby will use this method when printing instances of the class. ACM Learning Center -- Ruby Learning Path Copyright © 2011, Ruby Power and Light, LLC

Upload: rajul-srivastava

Post on 07-Nov-2015

217 views

Category:

Documents


0 download

DESCRIPTION

Ruby

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