Ruby“Hello World” in RubyEuclid’s algorithmGeneral principlesNumbersOther data typesOperatorsAssignment and alias statementsif statementsunless statementscase and ===Loops in RubyLoop controlsExceptionsBlocksDefining methodsDefining classesCalling methodsIteratorsSlide 20Example use of an iteratorString#each_charBlocks againSimplest use of yieldMy version of loopFibonacci numbersPassing a parameter to the blockReturning a value from a coroutineRegular expressionsArraysHashesAdding and removing methodsAttributes (instance variables)Shorthand for getters and settersAccess controlsevalprintf and friendsSome File < IO methodsSome File methodsStreamsSome String methodsSome more String methodsSome Array methodsChainingContextMore iteratorsProcsProcs are closures, tooProcs as parametersReflectionUndefined methodsAdding methods to a classModulesMetaprogrammingThe command lineLooking aheadTutorialsThe EndJan 13, 2019Ruby(Bet you can’t do this in Java!)“Hello World” in Rubyputs "Hello World!"Euclid’s algorithmdef euclid x, y while x != y if x > y then x -= y end if y > x then y -= x end end xendputs "Enter two numbers: "STDOUT.flushx = Integer(gets)y = Integer(gets)puts "The GCD of #{x} and #{y} is #{euclid x, y}“Enter two numbers: 24108The GCD of 24 and 108 is 12General principlesEverything is dynamic and may be changedAll values are objects (there are no “primitives”)Variables are typeless and need not be declaredRuby avoids unnecessary punctuationA statement on a line by itself needs no semicolonMultiple statements on a line are separated by semicolonsA line is continued if it ends in an operator, comma, or backslashParameters to a method don’t usually need parenthesesConditions (in if, while, etc.) usually don’t need parenthesesCorrect capitalization is required, not optionalConvention: Multiword variables use underscores, not camelCaseConvention: Standard indentation is two spacesNumbersNumbers may be written in decimal, hexadecimal, octal, or binaryDecimal: 3405691582Hex: 0xCAFEBABE or 0XCAFEBABEOctal: 031277535276 or 0o31277535276Binary: 0b11001010111111101011101010111110 or 0Betc.Numbers larger than four bytes are automatically treated as Bignum objectsFor readability, numbers may contain (but not begin or end with) underscoresExamples: 3_405_691_582, 0b_111_101_101Integers may be indexed to retrieve their bitsExample: 5.step(0, -1) { |i| print 6[i] } 000110Other data typesStrings can be singly quoted or doubly quotedDoubly quoted strings can interpolate values for #{expression} and for #@variable, and allow the usual escape charactersIn a singly quoted string, \' is the only recognized escape characterStrings are not immutableArrays are untyped and expandable, for example [1, 2, "hi"]Ruby has hashes: { :banana 'yellow', :cherry => 'red' }Ruby has regular expressions, dates, and timesRuby has ranges, such as 1..10Ruby has symbols, which stand for themselvesYou can think of them as immutable stringsExamples are :banana and :cherrySince they are immutable, they make good keys for hashesThey are also often used to refer to methods and variables: attr :do_itOperatorsAlmost all the Java operators, except ++ and --Ruby uses :: to mean the same as . in JavaRuby uses =~ and !~ for Perl-style regular expressions** is the exponentiation operator+ is used to concatenate stringsThere is a to_s method for converting other things to strings.. is an inclusive range, ... is an exclusive rangeSo 1..4 and 1...5 both mean 1, 2, 3, 40..k is a range object, but [0..k] is an array with one element, a rangedefined? is a prefix operator that returns a true value or nilRuby has both !, &&, || and also not, and, orPrecedence is ! > && > ||, but not > and == orAssignment and alias statementsAssignment statements use =, +=, *=, etc.You can have multiple assignment: x, y = y, x swaps the values of x and yRuby does not have the ++ and -- operatorsYou can create a new name for a method, operator, global variable, or regular expression backreferenceSyntax: alias new_name original_nameExample: alias display putsif statementsMulti-line version:if condition then codeelsif condition then codeelse codeendThe “then” is optional at the end of a lineSingle-line versions:if condition then code elsif condition then code else code end“then” is required to separate condition from codestatement if conditionunless statements“unless” means “if not”Multi-line version:unless condition then codeelse codeendThe “then” is optional at the end of a lineSingle-line versions:unless condition then code else code end“then” is required to separate condition from codestatement unless conditioncase and ===case expr_1 when expr_2 then code when expr_3, ..., expr_n then code else codeendCases do not fall through; no break is neededComparisons use expr_n === expr_1and not the other way aroundexpr_n === expr_1 has many meaningsSimple equality testexpr_1 =~ expr_nexpr_n.kindof? expr_1expr_n.include? expr_1The === operator has the misleading name “case equality operator”Loops in RubyRuby has several loopswhile condition do statementsendbegin statementsend while conditionuntil condition statementsendbegin statementsend until conditionfor variable in range do statementsendloop do statementsendstatement while conditionstatement until conditionloop { statements }However, loops are not used as often in Ruby as in other languagesInstead, Ruby programmers use iterator methodsLoop controlsbreak gets you out of loopsWithin a loop, next jumps to just before the loop testWithin a block, next exits the block with nilretry restarts the loop body after reevaluating the condition or getting the next iterated elementWithin a loop, redo restarts the loop body, but does not reevaluate the condition or get the next iterated elementWithin a block, redo restarts the yield or callExceptionsraise message raises a RuntimeErrorraise exception raises an error of the given typeraise exception, messagerescuerescue ExceptionType, ..., ExceptionTyperescue ExceptionType, ..., ExceptionType => variableCatches exceptions within a method, or within a begin...end block, or can be used as a
View Full Document