world wide web万维网英文课件:ch14-Introduction to Ruby

上传人:大米 文档编号:567677449 上传时间:2024-07-22 格式:PPT 页数:37 大小:1,024KB
返回 下载 相关 举报
world wide web万维网英文课件:ch14-Introduction to Ruby_第1页
第1页 / 共37页
world wide web万维网英文课件:ch14-Introduction to Ruby_第2页
第2页 / 共37页
world wide web万维网英文课件:ch14-Introduction to Ruby_第3页
第3页 / 共37页
world wide web万维网英文课件:ch14-Introduction to Ruby_第4页
第4页 / 共37页
world wide web万维网英文课件:ch14-Introduction to Ruby_第5页
第5页 / 共37页
点击查看更多>>
资源描述

《world wide web万维网英文课件:ch14-Introduction to Ruby》由会员分享,可在线阅读,更多相关《world wide web万维网英文课件:ch14-Introduction to Ruby(37页珍藏版)》请在金锄头文库上搜索。

1、Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-WesleyChapter 14Introduction to Ruby14-2Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.1 Origins and Uses of RubyDeveloped by Yukihiro Matsumoto about 1996Purely interpretedSomewhat easier learning be

2、cause of simple structureNotable characteristicsRegular expressions based on PerlDynamic classes based on JavaScript14-3Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.2 Scalar Types and Their OperationsThree categories of dataScalrsArraysHashesAll values are objects, i

3、ncluding numeric values14-4Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.2 Numeric LiteralsNumeric data are descendants of class NumericFloat and IntegerFixnum and BignumInteger literals are Fixnum unless too large, then BignumUnderscores can punctuate integer literal

4、sFloat literals may not have a decimal point first or last14-5Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.2 String LiteralsSingle or double quotedDouble quoted has escape characters and expression interpolationExpression is specified by #Single quoted have not escap

5、e characters or expression interpolationq$.$ for a single quoted string$ can be other characters) at the endQ$.$ for a double quoted string14-6Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.2 Variables and Assignment StatementsVariable names indicate category of variab

6、lesVariables are not formally declared and do not have a fixed typeAn identifier begins with a lower case letter or underscore followed by letters and/or digits and/or underscoreVariables are all references to objectsAn unassigned variable has value nilNamed constants are named like variables but ha

7、ve names that begin with a capital letterThere are some implicit variables such as $_Assignment statements in Ruby are the same as in the C/C+/Java family14-7Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.2 Numeric OperatorsStandard operators: + - * / %Integer/Integer

8、is integer* for exponentiationMissing: + and Math module: cos, sin, log, sqrt, The interactive Ruby interpreter irb takes experssions and responds with the values14-8Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.2 String MethodsCatenation is indicated by + appends its

9、 right operand to the leftSimilar to an assignment operator+= is a synonymcapitalize, chop, chomp, upcase, These create new stringsMutator versions capialize!, chop!, chomp!, upcase! modify the string14-9Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.2 String Character

10、 Access index Single character reference returns the ASCII code of a characterindex=first-char, numer-of-chars gets a substringfirst-char, numer-of-chars= replaces a substring= compares strings for equality based on contentequal? compares for the same objecteql? compares for type and value compares

11、two strings returning -1 if the first is smaller, 0 if they are equal, +1 if the second is smaller* is used to repeat a string: “x” * 3 is “xxx”14-10Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.3 Screen OutputOperator puts displays a string on standard outputA new li

12、ne is added to the outputOperator print displays a string without the new line14-11Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.3 Keyboard InputFunction gets gets a line of input from the console (keyboard)gets.chomp returns the next lline of input with out the termi

13、nating new linegets.to_i returns the next line of input converted to an integergets.to_f returns the next line of input converted to a floatExample quadeval.rb illustrates console input and outputRun with the commandruby quadeval.rb14-12Copyright 2008 Pearson Education, Inc. Publishing as Pearson Ad

14、dison-Wesley14.4 Control ExpressionsA Boolean expressionAny value but nil is considered trueComparison operatorsUsual: = != =Compare for order: Compare for type and value: eql?Compare for equality of object: equal?Operator precedence and associativityAssignments can be used as control expressionsnex

15、t = getsThis is true as long a there is more inputBecomes false when input is exhausted14-13Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.4 Selection and Loop StatementsIf statementif control-expressionstatementselsif control-expressionstatementselsestatementsendelsif

16、 can be repeated any number of times (including 0)14-14Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.4 UnlessReverses if, no else or elsifunless control-expressionstatementsend14-15Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.4 Case Sy

17、ntaxcase expressionwhen value then- statement sequencewhen value then- statement sequenceelse- statement sequenceend 14-16Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.4 Case SemanticsValue is matched to whens using =Defined for all built-in classesIf the when value i

18、s a class, the comparison is true if the case value is an object of the class or one of its superclassesIf the value is a range, the case value matches if it is in that rangeIf the when value is a regular expression, the match is based on pattern matchingWhens do not cascade, so no break statements

19、are needed14-17Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.4 Case ExpressionSyntaxcasewhen Boolean expression then expression.when Boolean expression then expressionelse expressionendThe first true Boolean expression causes the matching expression to be evaluated as

20、 the value of the caseThe else expression is used if none of the Booleans are true14-18Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.4 LoopsWhile loop repeats while control expression is trueUntil loop repeats until control expression is trueloop introduces an infinit

21、e loopA code block is a sequence of statements delimited by braces or by keywords begin and endThe loop keyword is followed by a code blockExit from the loop is by the break statementThe next statement causes control to go back to the beginning of the code blockIterator methods are an important repe

22、tition construct in Ruby14-19Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.5 Fundamentals of ArraysRuby arrays are dynamic in size and can store different types of data in different elementsCreating an arrayArray.new(size)Array.new(size, value)A literal list such as 2

23、, 4, 6Element access through subscript subElement assignment through sub=14-20Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.5 The for-in StatementSyntaxfor variable in liststatementsendThe variable takes on each value in the listThis is not a reference but a value cop

24、y14-21Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.5 Build-In Methods for Arrays and Listspush inserts at the end of a listpop removes from the end of a list and returns the valueunshift inserts at the beginning of a listshift removes from the front of a list and ret

25、urns the valueArrays catenated with +Method reverse returns a reversed copyMethod reverse! reverses the arrayinclude? searches an arraysort sorts an array, returns a new array14-22Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.5 An ExampleThe process_names.rb example i

26、llustrates using arrays14-23Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.6 HashesHashes are like arrays but use string indexes Indexes are keys and elements are valuesHash elements are not orderedCreating a HashHash.newLiteral hash as in “a”=1, “b”=2Element access us

27、ing string subscriptsElements are added by using assignmentElements are removed using delete methodThe clear method removes all elementshas_key? checks if a string is a key in a hashMethods keys and values return arrays of the respective components14-24Copyright 2008 Pearson Education, Inc. Publishi

28、ng as Pearson Addison-Wesley14.7 MethodsMethods can be defined outside classeWhen a method is called without an object reference, the default is self14-25Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.7 Fundamentals of MethodsMethod syntaxdef name ( formal-parameters )

29、statementsendParentheses can be omitted if there are no formal parametersReturn statement ends execution of the methodWith a value, it returns the value as the value of the methodIf no return ends a method, the last expression is the value of the method14-26Copyright 2008 Pearson Education, Inc. Pub

30、lishing as Pearson Addison-Wesley14.7 Local VariablesVariables used in a method are local to the methodGlobal variables with the same name are hiddenLocal variable names must begin with a lowercase letter or an underscoreThe lifetime of a local variable from its creation to the end of the execution

31、of the method14-27Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.7 ParametersParameters are passed by value unless arrays and hashesArrays and hashes are passed by referenceThe number of actual parameters must match the number of formal parametersIf the last formal par

32、ameter is preceded by an asterisk, it receives all actual parameters not matched to earlier formal parametersFormal parameters can be assigned default values, so the corresponding actual parameter may be omittedIf a hash literal is the last actual parameter, the curly braces are not requiredIn this

33、case symbols are conventionally used as the keysA symbol is an unquoted string preceded by a colonExample method median computes the median of an array parameter14-28Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.8 Basics of ClassesSyntaxclass class-nameendClass names

34、begin with an uppercase letterInstance variables have instances for each object Names begin with Constructor is named initializeExample class Stack2_class implements a stack classMembers can by dynamically added and removed from a classMethod remove_method removes a method14-29Copyright 2008 Pearson

35、 Education, Inc. Publishing as Pearson Addison-Wesley14.8 Access ControlThree levelsPublic: every method has accessPrivate: only methods of the object have accessPrivate methods may not be invoked with an object reference, so must default to selfDifferent from C+ and JavaProtected: only methods of t

36、he class or subclasses have accessInstance data is private and that cannot be changedAccess control methods change access levelInvoked without parameters change the default for following methodsInvoked with parameters, these are symbols naming methods that have access changed14-30Copyright 2008 Pear

37、son Education, Inc. Publishing as Pearson Addison-Wesley14.8 AttributesMethod addr_reader takes symbol arguments and defines get methods named after the symbolsaddr_reader :valDefines a method named val that returns the value of valMethod addr_writer takes symbol arguments and defines an assignment

38、methodaddr_writer :valDefines a method named val= that allows assignment to the attribute as in obj.val = 17;14-31Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.8 InheritanceSyntaxclass My_Subclass Base_classAccess level of a method can be changed in a subclassA method

39、 can be made private and, thus, inaccessible through that subclassModules define namespaces that are often used to hold sets of methodsModules may be mixed in to classes, providing methods to the class by a non-inheritance route14-32Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addiso

40、n-Wesley14.9 Code Blocks and IteratorsA code block is a sequence of statements delimited by braces or by do/endA code block can have parameters, listed at the beginning of the block, surrounded by vertical bars: |a, b|A code block may be passed to a method call, following the actual parameters of th

41、e callIn the method body, a call to yield will executed the blockActual parameters of the call are matched with the block parametersAn iterator applies a block to the values in a list14-33Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.9 Built-in Iteratorseach is a meth

42、od of arrays and takes a block that has one parameterThe block is executed with the block parameter taking each element of the list in turnThe upto method applies to integers and takes an integer parameter and a block with one parameterThe block is executed for each value in the range from the targe

43、t integer to the actual parameter, inclusiveThe collect method creates an array from the results of applying a block to each element in an array14-34Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.10 Pattern MatchingPattern matching in Ruby is based on pattern matching

44、in Perl14-35Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.10 Basics of Pattern MatchingPatterns are delimited by slashes= is the pattern matching operatorThe split method is used to split a string with separators given by a regular expressionThe example word_table.rb

45、uses the split method to divide up input lines into wordsA hash is used to count word frequencies14-36Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.10 Remembering MatchesParts of a regular expression pattern can be enclosed in parenthesesIf there is a match, the varia

46、bles $1, $2 hold the strings matched by the parenthesized partsIf there is a match, $, $& and $ hold the part of the target before the match, the part matched and the part after the match14-37Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley14.10 SubstitutionsMethod sub substitutes its second parameter for the first match found of the first parameterMethod gsub is similar but substitutes for all matches Both methods create new stringssub! and gsub! change the target stringThe i modifier on a pattern causes the match to ignore letter case

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 高等教育 > 研究生课件

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号