190 likes | 443 Views
Section with Kiyoshi (Slides adapted from Harrison Ting’s). Ruby!. Readings. The Ruby Programming Language Read Chapter 1 Skim Chapters 2-7 Read sections 8.9 and 8.10. Running ruby. ruby: execute from command line ruby myProgram.rb irb : interactive command line interpreter
E N D
Section with Kiyoshi (Slides adapted from Harrison Ting’s) Ruby!
Readings The Ruby Programming Language Read Chapter 1 Skim Chapters 2-7 Read sections 8.9 and 8.10
Running ruby • ruby: execute from command line • ruby myProgram.rb • irb: interactive command line interpreter • Write program in the command line or… • Import ruby file: source ‘myProgram.rb’ • Run ruby file: load ‘myProgram.rb’ • SciTE: IDE bundled with ruby install • Sorry Mac and linux users, Windows only • Edit • Execute
Example #1: Classes • Files: • greeter.rb • spanishGreeter.rb • copyGreeter.rb • greeterCounter.rb • Constructor • Instance methods and variables • Subclassing • Inheritance • super • Class methods and variables
Example #2: Control • Files • printTwice.rb • Adding a method to a class
Example #3: Control cont. • Files • firstElement.rb • firstElementWithYield.rb • firstElementWithYieldAndEnumerable.rb • Adding a method to a module • Blocks and Iterators • yield • Can yield more than one value
Example #4: eval’s • Files • eval.rb • classEval.rb • eval vs. class_eval • class_eval executes in the context of the class • eval executes in the current context
Example #5: Regular Expressions Use for pattern matching
Regular Expressions cont. • Literals • /1/.match("012") – matches • "012".match(/1/) – does the same thing • /1/.match("789") – doesn’t match
Regular Expressions cont. • Character classes • /[db]og/.match("dog") • /[db]og/.match("bog") • /[0-9]/.match("Ruby 123") • /[a-z]/.match("Ruby 123") • /[A-Z]/.match("Ruby 123") • /[a-zA-Z0-9]/.match("Ruby 123") • /[^Rub]/.match("Ruby 123")
Regular Expressions cont. • Special character class: “.” • /.og/.match("dog")
Regular Expressions cont. • Repetition • “?” matches 0 or 1 • /ruby?/.match("rub") • /ruby?/.match("rubyyy") • “*” matches 0 or more • /ruby*/.match("rub") • /ruby*/.match("rubyyy") • “+” matches 1 or more • /ruby+/.match("rub") • /ruby+/.match("rubyyy")
Regular Expressions cont. • Putting it all together • /[aeiou]+/.match("aardvark")
Regular Expressions cont. • (, ), [, ], {, }, ., ?, +, *, |, ^, $, \ have special meaning • Escape each one to use it literally • Files • regexp.rb • See section 9.2 for more information
Example #6: Sorting • Files • absoluteSort.rb
Example #7: method_missing • Files • methodMissing.rb
Example #8: Hash • Files • hashMe.rb