Automation: Time to learn RubyWhy do we want a scripting language?Some examplesSome downsides ..Ruby .. Some backgroundOkay … Lets get startedBasic syntax rulesControl structuresControl structures ..ArraysHashesStrings and regular expressionsStrings and regular expressions..Code blocks and yieldBasic file I/OSlide 16ClassesTopics Useful for Project TestingControlling processesControlling processes: TimeoutSlide 21Network ConnectionsHandling Exceptions a.k.a Having to code in the real worldRuby unit testingUseful resourcesParting thoughts ..Announcements ..01/14/19 15-441 Ruby Recitation 1Automation:Time to learn Ruby15-441 Spring 2010, Recitation 5 Your Awesome TAs01/14/19 15-441 Ruby Recitation 2Why do we want a scripting language?•Why not Assembly, C, C++, Java ..•Much easier to program inShorten the edit-develop-compile cycle•Re-use existing componentsE.g. TCP server, retrieve web pages•Easy short-cuts for common operationsText-processing, Strings, Regexp•Fewer low-level hasslesTypes, memory management etc01/14/19 15-441 Ruby Recitation 3Some examples•Shell-script•Sed/Awk•Perl•Python•Tcl/Tk•Smalltalk•…..01/14/19 15-441 Ruby Recitation 4Some downsides .. •Most commonly cited: PerformanceNot good for ..Compute-intensive operationsCreating data structures, algorithmsLess true as hardware makes up ..•Common problem: unpredictable ..Interpreted, not compiledDon’t require types/initialization•Another common problem: mysterious..From the manpage: Perl actually stands for Pathologically Eclectic Rubbish Lister, but don't tell anyone I said that.01/14/19 15-441 Ruby Recitation 5Ruby .. Some background•Often called “multi-paradigm”Procedural + OOP + Functional featuresBut a high-level scripting language!•Philosophy: Principle of Least SurpriseWhat you expect is most likely what you get•FeaturesTruly object-orientedSupport for Perl-like regular expressionsSyntax a lot like Python/Perl•Trivia: The language was created by Yukihiro "Matz" Matsumoto , 199501/14/19 15-441 Ruby Recitation 6Okay … Lets get startedFile: Helloworld.rb#! /usr/bin/ruby #<-- # please have useful comments# unlike the one here!def sayHelloworld(name) #<-- puts "Hello world #{name} " #<--end #<-- sayHelloworld(“kaushik") #<--01/14/19 15-441 Ruby Recitation 7Basic syntax rules•Comments start with a # character, go to EOL•Each expression is delimited by ; or newlinesUsing newlines is the Ruby way•Local variables, method parameters, and method names should all start with a lowercase letter or _•Global variables are prefixed with a $ sign •Class names, module names, and constants should start with an uppercase letter•Class instance variables begin with an @ sign01/14/19 15-441 Ruby Recitation 8Control structures•The usual suspects if, while, for, untilIterators: each•if exampleif (score > 10)puts "You have cleared the checkpoint”elsif (score > 5) # this is cool!puts " You have passed”elseputs "You have failed :-(”end01/14/19 15-441 Ruby Recitation 9Control structures .. •while exampleteam = 1while (team <= maxteam)result = grade(team)team = team + 1end•Shortcuts:puts "Passed!" if (score >= 10)score = score+1 while (score <= 100)01/14/19 15-441 Ruby Recitation 10Arrays• array1 = Array.newarray1[0] = 1array1[1] = 2index = 0#traditional waywhile (index < array1.size)puts array1[index].to_sindex = index + 1 end• array2 = [3, 4, 5, 6]array2.each {|x| puts x} #Ruby way•Useful functions: reverse, sort01/14/19 15-441 Ruby Recitation 11Hashes•Most amazing feature of scripting languagesAlong with regular expressions•hash1 = Hash.newhash1["champions"] = "steelers”hash1["runnersup"] = "seahawks”hash1.each do |key,value| puts "#{key} are #{value}”endhash1.delete("runnersup")•e.g. where you might use thisnick2ip["nick"] = ipaddr_connect01/14/19 15-441 Ruby Recitation 12Strings and regular expressions•Stringss = ‘This is a new string ‘ earl = ”Earl”s = “My name is #{earl}”answer = 42s = ‘The answer name is ‘ + answer.to_s•Many useful functions: to_i,upcase,downcase,reverseNote: need explicit to_i (unlike perl) •Regular expression matchingif string =~ / Hello\sWorld/puts "the string is Hello World”end •Commonly used regular expressions: \s, \w, \d, ., *, +01/14/19 15-441 Ruby Recitation 13Strings and regular expressions..•Substitution:language.sub(/Perl/,'Ruby') #first language.gsub(/Perl/,'Ruby') #all•Interested in not only matching but also values?s="12:50am” if s=~/(\d+):(\d+)(\w+)/puts "Hour:#$1, Min:#$2 #$3”end•split examplehelloworld=‘Hello World’(hello,world) = helloworld.splitnumbers=‘1,2,3,4,5’splitarray = numbers.split(‘,’)01/14/19 15-441 Ruby Recitation 14Code blocks and yield•Code blocks defined by {} or do-end •yield example:def method_yieldsyieldendmethod_yields { puts "Came here"}•Fancier example:def fibUpTo(max) i1, i2 = 1, 1 # parallel assignment while i1 <= max yield i1 i1, i2 = i2, i1+i2 endendfibUpTo(1000) { |f| print f, " " }•each and iterators defined this way01/14/19 15-441 Ruby Recitation 15Basic file I/O•Common printing tasks: printf, print, puts•Getting user input: gets•Reading a file1. aFile = File.open("testfile”,”r”)# process the file line by lineaFile.each_line do |line|line_new = line.chompputs line_newend2. IO.foreach(“testfile”) {|f| puts f}•Getting rid of pesky EOL: chomp, chomp!, chop, chop!•Alternative reading whole file into arrayarr = IO.readlines("testfile”)01/14/19 15-441 Ruby Recitation 16Basic file I/O•Writing to a filewFile = File.open("debuglog",'w') wFile.puts "debug message\n"wFile.close01/14/19 15-441 Ruby Recitation 17Classesclass IRC #class name starts in capitalattr_reader :server,:port #shortcut for access outside attr_writer :nick #shortcut for writing @nick outside def initialize(server, port, nick, channel)@server = server #instance variables start with @ @port = port @nick = nick @channel = channeldef connect #another method#instance variables don’t need declaration@server_connection = TCPSocket.open(@server,@port)enddef send(s)@server_connection.send(s)endendircc = IRC.new($SERVER,$PORT,’’,’’) #create an object of type IRCircc.nick = ‘kaushik’ #nick is writeable end#constructor01/14/19 15-441 Ruby Recitation 18Topics Useful for Project Testing•Controlling processes•Network
View Full Document