Introduction to Ruby WING Group Meeting 9 Jun 2006 Min-Yen Kan WING Group Meeting 9 Jun 2006 Min-Yen Kan.

Slides:



Advertisements
Similar presentations
Perl Practical Extration and Reporting Language An Introduction by Shwen Ho.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
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.
A Guide to Unix Using Linux Fourth Edition
Introduction to PHP MIS 3501, Fall 2014 Jeremy Shafer
The Web Warrior Guide to Web Design Technologies
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Scripting with Ruby What is a scripting language? What is Ruby?
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
PHP Workshop ‹#› PHP: The Basics. PHP Workshop ‹#› What is it? PHP is a scripting language commonly used on web servers. –Stands for “PHP: Hypertext Preprocessor”
Ruby (on Rails) CSE 190M, Spring 2009 Week 1. The Players Kelly "Everyday I'm Hustlin' " Dunn Kim "Mouse" Todd Ryan "Papa T" Tucker.
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
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
CMSC 330: Organization of Programming Languages Ruby Hash Tables (and other topics)
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Introduction to Perl Practical Extraction and Report Language or Pathologically Eclectic Rubbish Lister or …
Introduction to Python
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
An Introduction to Unix Shell Scripting
Nael Alian Introduction to PHP
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Ruby on Rails. What is Ruby? Programming Language Object-oriented Interpreted.
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Introduction to Perl Yupu Liang cbio at MSKCC
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
5 1 Data Files CGI/Perl Programming By Diane Zak.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
RUBY by Ryan Chase.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
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.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
1 PHP Intro PHP Introduction After this lecture, you should be able to: Know the fundamental concepts of Web Scripting Languages in general, PHP in particular.
Introduction to information systems RUBY dr inż. Tomasz Pieciukiewicz.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Presented By P.SRIVIDYA 085D1A0552 Programming Language.
Web Database Programming Using PHP
CS 330 Class 7 Comments on Exam Programming plan for today:
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
DBW - PHP DBW2017.
PHP Introduction.
Chapter 14 Introduction to Ruby.
Introduction to Python
Ruby Testing 2, 11/9/2004.
Presentation transcript:

Introduction to Ruby WING Group Meeting 9 Jun 2006 Min-Yen Kan WING Group Meeting 9 Jun 2006 Min-Yen Kan

What is Ruby? An interpreted language a.k.a dynamic, scripting e.g., perl Object Oriented Single inheritance High level Good support for system calls, regex and CGI Relies heavily on convention for syntax An interpreted language a.k.a dynamic, scripting e.g., perl Object Oriented Single inheritance High level Good support for system calls, regex and CGI Relies heavily on convention for syntax

Hello World #!/usr/bin/env ruby puts “Hello world” $ chmod a+x helloWorld.rb $ helloWorld.rb Hello world $ #!/usr/bin/env ruby puts “Hello world” $ chmod a+x helloWorld.rb $ helloWorld.rb Hello world $ shell script directive to run ruby Needed to run any shell script Call to method puts to write out “Hello world” with CR Make program executable

Basic Ruby Everything is an object Variables are not typed Automatic memory allocation and garbage collection Comments start with # and go to the end of the line You have to escape \# if you want them elsewhere Carriage returns mark the end of statements Methods marked with def … end Everything is an object Variables are not typed Automatic memory allocation and garbage collection Comments start with # and go to the end of the line You have to escape \# if you want them elsewhere Carriage returns mark the end of statements Methods marked with def … end

Control structures If…elsif…else…end case when then … else… end unless … end while … end until … end #.times (e.g. 5.times()) #.upto(#) (e.g. 3.upto(6)).each {block} If…elsif…else…end case when then … else… end unless … end while … end until … end #.times (e.g. 5.times()) #.upto(#) (e.g. 3.upto(6)).each {block} elsif keeps blocks at same level case good for checks on multiple values of same expression; can use ranges grade = case score when then “A” when then “B” else “C” end Looping constructs use end (same as class definitions) Various iterators allow code blocks to be run multiple times

Ruby Naming Conventions Initial characters Local variables, method parameters, and method names  lowercase letter or underscore Global variable  $ Instance variable Class variable  Class names, module names, constants  uppercase letter Multi-word names Instance variables  separate words with underscores Class names  use MixedCase End characters ? Indicates method that returns true or false to a query ! Indicates method that modifies the object in place rather than returning a copy (destructive, but usually more efficient) Initial characters Local variables, method parameters, and method names  lowercase letter or underscore Global variable  $ Instance variable Class variable  Class names, module names, constants  uppercase letter Multi-word names Instance variables  separate words with underscores Class names  use MixedCase End characters ? Indicates method that returns true or false to a query ! Indicates method that modifies the object in place rather than returning a copy (destructive, but usually more efficient)

Another Example class Temperature Factor = 5.0/9 def = c end def = (f - 32)*Factor end def end def as_F / Factor) + 32 end end # end of class definition class Temperature Factor = 5.0/9 def = c end def = (f - 32)*Factor end def end def as_F / Factor) + 32 end end # end of class definition Factor is a constant 5.0 makes it a float 4 methods that get/set an instance variable Last evaluated statement is considered the return value

Second Try class Temperature Factor = 5.0/9 attr_accessor :c def = (f - 32) * Factor end def f / Factor) + 32 end def initialize = c end t = Temperature.new(25) puts t.f # 77.0 t.f = 60 # invokes f=() puts t.c # class Temperature Factor = 5.0/9 attr_accessor :c def = (f - 32) * Factor end def f / Factor) + 32 end def initialize = c end t = Temperature.new(25) puts t.f # 77.0 t.f = 60 # invokes f=() puts t.c # attr_accessor creates setter and getter methods automatically for a class variable initialize is the name for a classes’ constructor Don’t worry - you can always override these methods if you need to Calls to methods don’t need () if unambiguous

Regular Expressions /[A-Z]/i /[^>]+/ / ]+/im / ]+>.* /im /[^\t]/ /([^\t]+)/ /^([^\t]+)\t([^\t]+)$/ /[A-Z]/i /[^>]+/ / ]+/im / ]+>.* /im /[^\t]/ /([^\t]+)/ /^([^\t]+)\t([^\t]+)$/ First class objects in ruby Sandwiched between // Quiz: How do you make a regexp for … ?

Input and Output - tsv files f = File.open ARGV[0] while ! f.eof? line = f.gets if line =~ /^#/ next elsif line =~ /^\s*$/ next else puts line end f.close f = File.open ARGV[0] while ! f.eof? line = f.gets if line =~ /^#/ next elsif line =~ /^\s*$/ next else puts line end f.close ARGV is a special array holding the command-line tokens Gets a line If it’s not a comment or a blank line Print it

Processing TSV files h = Hash.new f = File.open ARGV[0] while ! f.eof? line = f.gets.chomp if line =~ /^\#/ next elsif line =~ /^\s*$/ next else tokens = line.split /\t/ h[tokens[2]] = tokens[1] end f.close keys = h.keys.sort {|a,b| a b} keys.each {|k| puts "#{k}\t#{h[k]}" } h = Hash.new f = File.open ARGV[0] while ! f.eof? line = f.gets.chomp if line =~ /^\#/ next elsif line =~ /^\s*$/ next else tokens = line.split /\t/ h[tokens[2]] = tokens[1] end f.close keys = h.keys.sort {|a,b| a b} keys.each {|k| puts "#{k}\t#{h[k]}" } Declare a hash table Get lines without \n or \r\n - chomp split lines into fields delimited with tabs Store some data from each field into the hash Sort the keys - sort method takes a block of code as input each creates an iterator in which k is set to a value at each pass #{…} outputs the evaluated expression in the double quoted string

Blocks Allow passing chunks of code in to methods Receiving method uses “yield” command to call passed code (can call yield multiple times) Single line blocks enclosed in {} Multi-line blocks enclosed in do…end Can use parameters [ 1, 3, 4, 7, 9 ].each {|i| puts i } Keys = h.keys.sort {|a,b| a b } Allow passing chunks of code in to methods Receiving method uses “yield” command to call passed code (can call yield multiple times) Single line blocks enclosed in {} Multi-line blocks enclosed in do…end Can use parameters [ 1, 3, 4, 7, 9 ].each {|i| puts i } Keys = h.keys.sort {|a,b| a b }

Running system commands require 'find' Find.find('.') do |filename| if filename =~ /\.txt$/i url_output = filename.gsub(/\.txt$/i, ".html") url = `cat #{filename}`.chomp cmd = "curl #{url} -o #{url_output}"; puts cmd `#{cmd}` end require 'find' Find.find('.') do |filename| if filename =~ /\.txt$/i url_output = filename.gsub(/\.txt$/i, ".html") url = `cat #{filename}`.chomp cmd = "curl #{url} -o #{url_output}"; puts cmd `#{cmd}` end require reads in another ruby file - in this case a module called Find Find returns an array, we create an iterator filename to go thru its instances We create a new variable to hold a new filename with the same base but different.html extension We use backticks `` to run a system command and (optionally) save the output into a variable curl is a command in mac os to retrieve a URL to a file, like wget in unix

CGI example require 'cgi' cgi = CGI.new("html3") size = cgi.params.size if size > 0 # processing form in = cgi.params['t'].first.untaint cgi.out { cgi.html { cgi.head cgi.body { "Welcome, #{in}!" } } } else puts <<FORM Content-type: text/html Enter your name: <INPUT TYPE=TEXT NAME=t> FORM end require 'cgi' cgi = CGI.new("html3") size = cgi.params.size if size > 0 # processing form in = cgi.params['t'].first.untaint cgi.out { cgi.html { cgi.head cgi.body { "Welcome, #{in}!" } } } else puts <<FORM Content-type: text/html Enter your name: <INPUT TYPE=TEXT NAME=t> FORM end CGI requires library Create CGI object If parameters passed Process variable t untaint variables if using them in commands No parameters? create form using here document “ << “

Reflection...to examine aspects of the program from within the program itself. #print out all of the objects in our system ObjectSpace.each_object(Class) {|c| puts c} #Get all the methods on an object “Some String”.methods #see if an object responds to a certain method obj.respond_to?(:length) #see if an object is a type obj.kind_of?(Numeric) obj.instance_of?(FixNum)...to examine aspects of the program from within the program itself. #print out all of the objects in our system ObjectSpace.each_object(Class) {|c| puts c} #Get all the methods on an object “Some String”.methods #see if an object responds to a certain method obj.respond_to?(:length) #see if an object is a type obj.kind_of?(Numeric) obj.instance_of?(FixNum)

Summary High-level interpreted OO language No types; objects can reflect Native support of regex, iterators, system calls and CGI Relies on convention to limit variability OO encourages modular, maintainable code (if needed) Strong support for CGI and unit testing Only the basic here, multiple inheritance, exception handling, threading and testing are not covered High-level interpreted OO language No types; objects can reflect Native support of regex, iterators, system calls and CGI Relies on convention to limit variability OO encourages modular, maintainable code (if needed) Strong support for CGI and unit testing Only the basic here, multiple inheritance, exception handling, threading and testing are not covered

Modules Marshal - serialize data for load/save between program executions Date GetOptLong - manipulate command line arguments and switches Tempfile Mutex - semaphores for parallel code Net::URI Socket - different socket types CGI CGI::Session Marshal - serialize data for load/save between program executions Date GetOptLong - manipulate command line arguments and switches Tempfile Mutex - semaphores for parallel code Net::URI Socket - different socket types CGI CGI::Session

References rdoc - ruby javadoc rake - ruby make eruby - embedded ruby (in HTML; think php) rubygems - ruby package manager Irb - interactive ruby (good for debugging) Ruby on Rails (rails) For building web applications Based on Model-View- Contoller architecture further integration of ruby with database backend rdoc - ruby javadoc rake - ruby make eruby - embedded ruby (in HTML; think php) rubygems - ruby package manager Irb - interactive ruby (good for debugging) Ruby on Rails (rails) For building web applications Based on Model-View- Contoller architecture further integration of ruby with database backend Programming Ruby by Dave Thomas (the Pickaxe Book) ges/Ruby/QuickRef.html