8/22/201515-441 Ruby Recitation1 Automation: Time to learn Ruby 15-441 Spring 2010, Recitation 5 Your Awesome TAs.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Advertisements

Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
And other languages….  Selection Statements  Iterative Statements  Unconditional Branching  Not covered Guarded Commands.
Ruby: An introduction - Who am I? Maciej Mensfeld Presented by: Maciej Mensfeld Ruby: An introduction dev.mensfeld.pl github.com/mensfeld.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
17-Jun-15 Assorted Ruby Details. The command line irb starts an interactive Ruby interpreter ruby starts Ruby, with input from the command line End with.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
Guide To UNIX Using Linux Third Edition
ASP.NET Programming with C# and SQL Server First Edition
Scripting with Ruby What is a scripting language? What is Ruby?
Ruby (on Rails) CSE 190M, Spring 2009 Week 1. The Players Kelly "Everyday I'm Hustlin' " Dunn Kim "Mouse" Todd Ryan "Papa T" Tucker.
Python quick start guide
Introduction to Perl Part III By: Cedric Notredame Adapted from (BT McInnes)
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
The Ruby Programming Language
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
CMSC 330: Organization of Programming Languages 1 Overview of Ruby.
Lecture Note 3: ASP Syntax.  ASP Syntax  ASP Syntax ASP Code is Browser-Independent. You cannot view the ASP source code by selecting "View source"
CMSC 330: Organization of Programming Languages Ruby Hash Tables (and other topics)
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
SCRIPTING IN RUBY By Amber Bennett “Ruby is simple in appearance, but is very complex inside, just like our human body.” --Yukihiro Matsumoto.
1 Perl Perl basics Perl Elements Arrays and Hashes Control statements Operators OOP in Perl.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 13: An Introduction to C++
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Ruby on Rails. What is Ruby? Programming Language Object-oriented Interpreted.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
A very basic overview of Server-Side Scripting Or what is PHP, Perl, Python, Ruby and what can they do for me?
Trends in Scripting Languages History For me the purpose of life is partly to have joy. Programmers often feel joy when they can concentrate on the creative.
Introduction to Ruby WING Group Meeting 9 Jun 2006 Min-Yen Kan WING Group Meeting 9 Jun 2006 Min-Yen Kan.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Introduction to Perl Yupu Liang cbio at MSKCC
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
Scripting with Ruby What is a scripting language? What is Ruby?
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
RUBY by Ryan Chase.
Scripting with Ruby What is a scripting language? What is Ruby?
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Python Let’s get started!.
Week Four Agenda Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems Upcoming deadlines.
Introduction to information systems RUBY dr inż. Tomasz Pieciukiewicz.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Perl Subroutines User Input Perl on linux Forks and Pipes.
CMSC330 More Ruby. Last lecture Scripting languages Ruby language –Implicit variable declarations –Many control statements –Classes & objects –Strings.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Presented By P.SRIVIDYA 085D1A0552 Programming Language.
Ruby Getting started & Ruby.New Presented by Mario Tayah
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
Scope History of Ruby. Where can you use Ruby? General Features.
CS 371 Web Application Programming
What, Where and Why Swift
Automation: Time to learn Ruby
Chapter 14 Introduction to Ruby.
Chapter 10 Programming Fundamentals with JavaScript
Ruby Testing 2, 11/9/2004.
Tutorial 10: Programming with javascript
Presentation transcript:

8/22/ Ruby Recitation1 Automation: Time to learn Ruby Spring 2010, Recitation 5 Your Awesome TAs

8/22/ Ruby Recitation2 Why do we want a scripting language? Why not Assembly, C, C++, Java.. Much easier to program in  Shorten the edit-develop-compile cycle Re-use existing components  E.g. TCP server, retrieve web pages Easy short-cuts for common operations  Text-processing, Strings, Regexp Fewer low-level hassles  Types, memory management etc

8/22/ Ruby Recitation3 Some examples Shell-script Sed/Awk Perl Python Tcl/Tk Smalltalk …..

8/22/ Ruby Recitation4 Some downsides.. Most commonly cited: Performance  Not good for..  Compute-intensive operations  Creating data structures, algorithms  Less true as hardware makes up.. Common problem: unpredictable..  Interpreted, not compiled  Don’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.

8/22/ Ruby Recitation5 Ruby.. Some background Often called “multi-paradigm”  Procedural + OOP + Functional features  But a high-level scripting language! Philosophy: Principle of Least Surprise  What you expect is most likely what you get Features  Truly object-oriented  Support for Perl-like regular expressions  Syntax a lot like Python/Perl Trivia: The language was created by Yukihiro "Matz" Matsumoto, 1995Yukihiro "Matz" Matsumoto

8/22/ Ruby Recitation6 Okay … Lets get started File: Helloworld.rb #! /usr/bin/ruby #<-- # please have useful comments # unlike the one here! def sayHelloworld(name) #<-- puts "Hello world #{name} " #<-- end #<-- sayHelloworld(“kaushik") #<--

8/22/ Ruby Recitation7 Basic syntax rules Comments start with a # character, go to EOL Each expression is delimited by ; or newlines  Using 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 sign

8/22/ Ruby Recitation8 Control structures The usual suspects  if, while, for, until  Iterators : each if example if (score > 10) puts "You have cleared the checkpoint” elsif (score > 5) # this is cool! puts " You have passed” else puts "You have failed :-(” end

8/22/ Ruby Recitation9 Control structures.. while example team = 1 while (team <= maxteam) result = grade(team) team = team + 1 end Shortcuts: puts "Passed!" if (score >= 10) score = score+1 while (score <= 100)

8/22/ Ruby Recitation10 Arrays array1 = Array.new array1[0] = 1 array1[1] = 2 index = 0 #traditional way while (index < array1.size) puts array1[index].to_s index = index + 1 end array2 = [3, 4, 5, 6] array2.each {|x| puts x} #Ruby way Useful functions: reverse, sort

8/22/ Ruby Recitation11 Hashes Most amazing feature of scripting languages  Along with regular expressions hash1 = Hash.new hash1["champions"] = "steelers” hash1["runnersup"] = "seahawks” hash1.each do |key,value| puts "#{key} are #{value}” end hash1.delete("runnersup") e.g. where you might use this nick2ip["nick"] = ipaddr_connect

8/22/ Ruby Recitation12 Strings and regular expressions Strings s = ‘This is a new string ‘ earl = ”Earl” s = “My name is #{earl}” answer = 42 s = ‘The answer name is ‘ + answer.to_s Many useful functions: to_i,upcase,downcase,reverse  Note: need explicit to_i (unlike perl) Regular expression matching if string =~ / Hello\sWorld/ puts "the string is Hello World” end Commonly used regular expressions: \s, \w, \d,., *, +

8/22/ Ruby Recitation13 Strings 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 example helloworld=‘Hello World’ (hello,world) = helloworld.split numbers=‘1,2,3,4,5’ splitarray = numbers.split(‘,’)

8/22/ Ruby Recitation14 Code blocks and yield Code blocks defined by {} or do-end yield example: def method_yields yield end method_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 end fibUpTo(1000) { |f| print f, " " } each and iterators defined this way

8/22/ Ruby Recitation15 Basic file I/O Common printing tasks: printf, print, puts Getting user input: gets Reading a file 1. aFile = File.open("testfile”,”r”) # process the file line by line aFile.each_line do |line| line_new = line.chomp puts line_new end 2. IO.foreach(“testfile”) {|f| puts f} Getting rid of pesky EOL: chomp, chomp!, chop, chop! Alternative reading whole file into array arr = IO.readlines("testfile”)

8/22/ Ruby Recitation16 Basic file I/O Writing to a file wFile = File.open("debuglog",'w') wFile.puts "debug message\n" wFile.close

8/22/ Ruby Recitation17 Classes class IRC #class name starts in capital attr_reader :server,:port #shortcut for access outside attr_writer :nick #shortcut for outside def initialize(server, port, nick, channel) = server#instance variables = = = channel end def connect #another method #instance variables don’t need = end def end ircc = IRC.new($SERVER,$PORT,’’,’’)#create an object of type IRC ircc.nick = ‘kaushik’ #nick is writeable

8/22/ Ruby Recitation18 Topics Useful for Project Testing Controlling processes Network connections Handling exceptions Ruby unit testing

8/22/ Ruby Recitation19 Controlling processes System calls: system("tar xzf test.tgz") result = `date` IO.popen("ls -la") { |f| f.each_line {|filename| puts filename} } Forking a child if ((pid=fork) == nil) #in child exec(“sort testfile > output.txt“) else #in parent puts “the child pid is #{pid}” cpid = Process.wait puts “child #{cpid} terminated” end

8/22/ Ruby Recitation20 Controlling processes: Timeout Want to kill a child with a timeout  Frequently needed with network tests if ( (cpid = fork) == nil) while (1) # this is the child puts "first experiment" end else before = Time.now flag = 1 while (flag == 1) if ( (Time.now - before) > timeout) Process.kill("HUP",cpid) flag = 0 end sleep(sleepinterval) end

8/22/ Ruby Recitation21 Controlling processes: Timeout Want to kill a child with a timeout  Frequently needed with network tests require ‘timeout’ if ( (cpid = fork) == nil) # this is the child begin status = Timeout.timeout(5) do while (1) puts ”child experiment" end rescueTimeout::Error puts “Child terminated with timeout” end else puts Time.now Process.wait puts Time.now end

8/22/ Ruby Recitation22 Network Connections Simple tcp client require ‘socket’#use this module t=TCPSocket.new('localhost’,'ftp') t.gets t.close Simple tcp-echo server require ‘socket’ port = server = TCPServer.new(‘localhost’,port) while (session = server.accept) input= “#{session.gets}” session.print “#{input}\r\n” session.close end Slightly advanced server: extend GServer

8/22/ Ruby Recitation23 Handling Exceptions a.k.a Having to code in the real world f = File.open("testfile") begin #.. process rescue => err # local var to get exception #.. handle error puts “Error #{err}” ensure # executed always, put cleanup here f.close unless f.nil? end ensure: optional, goes after rescue retry: Use with caution – infinite loop!

8/22/ Ruby Recitation24 Ruby unit testing require socket require ‘test/unit’ Class TestIRC < Test::Unit::TestCase def setup # runs setup before every = end def teardown # runs teardown after every end def test_USER_NICK # can define many such give me :The ## lookup types of asserts under docs end

8/22/ Ruby Recitation25 Useful resources ri Class, ri Class.method irb: do quick test of code snippets And of course google

8/22/ Ruby Recitation26 Parting thoughts.. Why scripting: programmer efficiency Treat them as programming languages  It may be quicker to write a longer but cleaner script than an arcane one-liner Avoid getting stuck with religious battles  Perl vs Ruby vs Python Bottom-line  Be efficient  Write good code

8/22/ Ruby Recitation27 Announcements.. Collect HW1