The Ruby Programming Language

Slides:



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

Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.
Language of the Month If it’s December, it must be Ruby! Adam Coffman and Brent Beer.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Guide To UNIX Using Linux Third Edition
Scripting with Ruby What is a scripting language? What is Ruby?
A TOUR OF RUBY 2011 ACM Class, Dong Xie. What is Ruby?  Dynamic programming language  Complex but expressive grammar  A core class library with rich.
Introduction to Python
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Ruby! Ronald L. Ramos. What is Ruby? Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms,
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.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Learning Ruby - 10 Exploiting Classes. Ruby's Class Library Array - an ordered collection of objects Bignum - really big integer values Binding - remembering.
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.
+ Ruby and other programming Languages Ronald L. Ramos.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Scripting with Ruby What is a scripting language? What is Ruby?
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
RUBY by Ryan Chase.
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?
PHP vs. Python. Similarities are interpreted, high level languages with dynamic typing are Open Source are supported by large developer communities are.
Python Let’s get started!.
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
By Mr. Muhammad Pervez Akhtar
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Introduction to information systems RUBY dr inż. Tomasz Pieciukiewicz.
Ruby Tien Ho and Brandon Hostetter. Overview ▸ Object-oriented, functional, imperative, and reflective ▸ Interpreted language ▸ Influenced by Perl, Smalltalk,
Presented By P.SRIVIDYA 085D1A0552 Programming Language.
Programming in Go(lang)
Web Database Programming Using PHP
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 8: Namespaces, the class string, and User-Defined Simple Data Types.
C++ Lesson 1.
Information and Computer Sciences University of Hawaii, Manoa
Data Abstraction: The Walls
similar concepts, different syntax
Ruby Getting started & Ruby.New Presented by Mario Tayah
CS1022 Computer Programming & Principles
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
Chapter 3 Syntax, Errors, and Debugging
Python Let’s get started!.
Control Flow Constructs: Conditional Logic
Web Database Programming Using PHP
CS-104 Final Exam Review Victor Norman.
Shell Scripting March 1st, 2004 Class Meeting 7.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Classes, Objects, And Variables
MATLAB: Structures and File I/O
Chapter 14 Introduction to Ruby.
Introduction to Python
Ruby Testing 2, 11/9/2004.
FP Foundations, Scheme In Text: Chapter 14.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Coding Concepts (Basics)
Web DB Programming: PHP
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Quattor Advanced Tutorial, LAL
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Python Primer 1: Types and Operators
CISC101 Reminders All assignments are now posted.
Java Programming Language
PHP an introduction.
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Learning Python 5th Edition
Presentation transcript:

The Ruby Programming Language Igor Gaponenko March 7, 2003

W W W : who, when, why ? Who When Why Yukihiro Matsumoto (Matz) First introduced in December 1995 Since 2000 Ruby is more popular in Japan than Python Why “…a pragmatic language to get a job done…” “…more powerful than Perl and more truly object-oriented that Python…” “…influenced by Smalltalk, Perl, Python, Eiffel (Ada), Lisp, CLU and Sather...”

So what’s the Big difference ? (1) Language Ruby Added Ruby Took Away Smalltalk Object Orientation: “Everything is an object!“ Ruby, like Smalltalk uses single inheritance. However, Ruby uses a Mix-in concept to mimic multiple inheritance. Ruby isn't as strict as Smalltalk with regard to object, inheritance and class hierarchy; giving a programmer training wheels until true object oriented design is learned. Perl Scripting Power - Clean Object Orientation - Ruby was initially designed with OO in mind, whereas Perl was extended to support objects. Punctuation (Ruby uses $(globals), @(instance), @@(class) prefixes do denote variable scope, not data types).  Ruby eliminates a lot of Perl's syntax sugar without losing functionality making Ruby less cryptic. Scope rules in Ruby (default: local) eliminate the need for any 'my' declarations.

So what’s the Big difference ? (2) Language Ruby Added Ruby Took Away Python Exception Handling Exception handling Type coercion between small and long integers Mark and sweep garbage collection instead of a Ref-counter garbage collection. Inheritance / subclassing Ruby's instance variables are prefixed by a @ eliminating the need for 'self' declarations. Python treats types and classes differently, Ruby treats them the same. Tuples Eiffel Object orientation and simple syntax - Ruby is interpreted - Compilation is not required for Ruby Lisp Lambda expressions - Object orientation - All those parentheses

What Ruby is good for ? Text processing CGI programming Network programming XML programming GUI applications AI and Exploratory Mathematics General programming Prototyping Programming education  eXtreme programming Etc.

Feature Presentation

Program Layout : line-oriented Multiple expressions a = 1 b = 2; c = 3 d = 4 + 5 + 6 + 7 e = 8 + 9 \ + 10 Ruby is able to understand that the statement is incomplete. Tell Ruby explicitly that the statement will continue at the next line

Program Layout : code & data Ruby compiler treats this optional statement as the end of the program’s code <code> __END__ <data> The rest is treated as a data block. It can be read into the running program using the global IO object DATA.

Program Layout : BEGIN & END Optional block(-s) to be executed as the file being loaded before the “normal code” BEGIN { <begin code> } <normal code> END { <end code> Optional block(-s) to be executed after the program finished executing

Modules # “file1” module module File1Mod class A ... end # “main” module require “file1” load “/ruby/modules/file2.rb” a = File1Mod::A.new(...) b = Trig.sin(Trig::PI/2) # “file2” module module Trig PI = 3.14195 def sin(angle) ... end

Loading Modules “require” statement means that the module gets compiled at the same time its callers do “load” statement will cause recompilation of the specified module at the run-time. Similar to “eval” in Perl

Roles of Modules It’s a way of grouping together: methods classes constants Modules provide a namespace to prevent name clashes Modules implement the mixin facility => To be discussed later

Reserved Words __FILE__ and def end in or self unless __LINE__ begin defined? ensure module redo super until BEGIN break do false next rescue then when END case else for nil retry true while alias class elsif if not return undef yield

What Ruby programs are made from ? Modules Expressions Classes References Methods Blocks of Code Objects

Naming Conventions Begin with low case symbols : references method names Begin with upper case symbols : Class names Module names Constant names These rules are mostly conventions ! However in some cases they affect the way compiler treats the code (example: constants).

References & Objects Everything is an object ! References is the only way to interact with the objects. empty = nil # no object behind a = 1 # numeric object b = a # ‘b’ refers to the same object PI = 3.14195 # here be a constant c = [] # an empty Array object d = MyClass.new # an object of ‘MyClass’ # create an object representing a block of code e = proc { print “A block of code” } e.call # execute the block print e.id # unique object identifier print e.type.name # class name: “Proc”

Basic Types ( Classes ) Numbers Strings Arrays Hashes Ranges Symbols Regular expressions

Basic Types : Numbers # Integer numbers : auto-conversion 1234 # Fixnum 123_456 # Fixnum -5 # Negative Fixnum 123_456_789_000_123_456 # Bignum 0xaabb # Hexadecimal 0377 # Octal 0b0101010 # Binary ?a # Character code ?\C-A # Ctrl-A # Float numbers : map to “double” of the # current architecture 3.14 # Float 0.0314e2 # Float

Basic Types : Strings ‘hello’ # no substitution “hello\n” # insert EOL “\123mile” # “Smile” %q/no substitution here/ %Q/double quoted string/ # Concatenating strings a = “A &” + “ B” b = “Prefix” ’ and ’ “Suffix” # “Prefix and Suffix” # “here” documents print <<HERE Double quoted here document. It allows substitution. For example: b = #{b} HERE

Basic Types : Arrays a = [] # create empty array some = SomeClass.new # create an object b = [ 1, 3.14159, “Some string”, some ] # No multi-dimensional arrays – just arrays of references c = [ [ 1, 2, 3 ], ‘a’, 1.2 ] d = [ c, [ 4, 5 ] ] # Using arrays print c[0][0] # 1 print d[0][0][0] # 1 c[1] = ‘b’ # replace ‘a’ with ‘b’

Basic Types : Hashes colors = { “red” => 0xf00, “green” => 0x0f0, “blue” => 0x00f } property = { } # Create an empty hash property[‘WIDTH’] = 10.2 property[...

More About Hashes It’s not required that keys of the same hash had the same type What a mess !!! Any objects can be used as keys if: They have the method “hash“ returning a hash value The hash value does not change Hashes keeps references onto objects used as keys The only exception is objects of the class String. They are duplicated.

Basic Types : Ranges (as Sequences) 1..10 # inclusive range 1...10 # exclusive range (for last) ‘a’..’z’ 0..anArray.length # Operations digits = 1..10 digits.min # 1 digits.max # 10 digits.include?(5) # true # Converting to arrays (1..5).to_a # [1,2,3,4,5] (“bar”..”bat”).to_a # [“bar”,”bas”,”bat”]

More About Ranges Ranges are objects of Range class Each Range object has two references onto Fixnum objects (not lists) Ranges can be created based on any objects if: the corresponding class defines“succ” method (++ operator in C++) Objects are comparable using “” operator

Basic Types : Ranges (as Conditions) f = File.open( “somefile.txt” ) while f.gets print if /start/../end/ end f.close Print sets of lines of the input file, where the first line in each set contains the word “start” and the last line the word “end” somefile.txt ... Let’s start doing something... do-do-do The end.

Basic Types : Ranges (as Intervals) (1..10) === 5 # true (1..10) === 15 # false (1..10) === 3.14159 # true (‘a’.. ’f’) === ‘b’ # true (‘a’...’f’) === ‘f’ # false

Object-Oriented Regexp class Regular Expressions Full power of Perl + Object-Oriented Regexp class

Methods Lambda expressions (functions) … # Let’s define a trivial method def add( first, second ) first + second end # ...and use it a = add( 1 , 2 ) b = add 1, 2

Methods : default parameters Watch for parameters substitution in strings… def coolFriends( first = “me”, second = “me” ) “#{first} and #{second}” end # Let’s make friends print coolFriends print coolFriends( “Smith” ) print coolFriends( “Smith”, “Wesson” ) # Guess what we’ll see... me and me me and Smith Smith and Wesson

Methods : variable-length args The last (or the only) parameter may get the rest (0..n) arguments. This parameter is an object of Array type. def var( first, *rest ) print “first = “, first, “\n” print “rest has “, rest.length, “ elements\n” for arg in rest print arg, “, “ end # Let’s try this var 1 var 1, 2 # rest = [ 2 ] var 1, 2, 3 # rest = [ 2, 3 ]

Methods : associating w/ blocks (1) A block is called within a method using yield. A blocks is passed as the last parameter of the method. Watch for two methods to pass a block. def executeMe yield end # Let’s try this executeMe { print “Hello! I’m a block.\n” } executeMe do ...

Methods : associating w/ blocks (2) A block may be parameterized by passing parameters to yield. This techniques is used in iterators. def foreachElement(array) for e in array yield e # call a block and pass it a value end # Let’s try this fighters = [ “F-4”, “F-14”, “MIG-23”, “HARRIER” ] foreachElement fighters do |name| print “Got “, name, “\n”

Iterators Ruby does not have good loop constructs. There is more powerful technique of iterators. Iterators make use of methods associated with blocks. sum = 0; 10.downto( 0 ) { |x| sum += x } # x = 10,9, ... ,0 10.times { |x| print “X ” } # “X X X X X “ 10.step(16, 2) { |x| print x, “ “ } # “10 12 14 16 “ The built-in integer type has these (and more others) iterators. User defined classes may introduce its own iterators or mix-in the Enumerable module to get these iterators “(almost) for free”.

If and Case are Expressions ! (1) In Ruby if and case are not statements (as in C/C++). They are expressions. Remember ‘?’ operator in C++ ? colors = [ “red”, “green”, “blue” ] masks = if someName == “red” 0xf00 else if someName == “green” 0x0f0 0x00f end

If and Case are Expressions ! (2) Here is a combined example illustrating use of ranges in conditional expressions. rating = case votesCast when 0...10 then Rating::SkipThisOne when 10...50 then Rating::CouldDoBetter else Rating::Rave end

Classes : Constructor # Define the class class Song def initialize( name, artist, duration ) ... end def play print “Bla-bla-bla...” # Let’s create an object of the class song = Song.new( “Lullaby”, “Me”, 600.0 ) song.play song.type.name # “Song”

Classes : Instance Variables Instance variables (attributes) are prefixed with ‘@’. class Song def initialize( name, artist, duration ) @name, @artist, @duration = name, artist, duration end def name @name # Let’s create an object of the class and get # the name of the song. song = Song.new( “Lullaby”, “Me”, 600.0 ) print song.name # “Lullaby”

Classes : Readable Attrubutes Another way to define readable attributes class Song attr_reader :name, :artist, :duration def initialize( name, artist, duration ) @name, @artist, @duration = name, artist, duration end # Now all attributes are available song = Song.new( “Lullaby”, “Me”, 600.0 ) print song.name # “Lullaby” print song.artist # “Me”

Classes : Writable Attributes class Song attr_writer :name, :artist, :duration ... end # Now all attributes are modifiable song = Song.new( “Lullaby”, “Me”, 600.0 ) song.name = “Another one” song.artist = “Him”

Classes : Virtual Attributes class Song ... def durationInMinutes @duration / 60.0 end define durationInMinutes=(duration) @duration = 60.0 * duration # Try virtual attributes song = Song.new( “Lullaby”, “Me”, 600.0 ) print song.durationInMinutes # “10.0” song.durationInMinutes = 5.5

Classes : Class Variables Class variables (attributes) are prefixed with ‘@@’. class Song @@plays = 0 def initialize( name, artist, duration ) ... end def play @@plays += 1 song = Song.new( “Lullaby”, “Me”, 600.0 ) song.play # @@plays -> 1 song.play # @@plays -> 2

Classes : Class Methods Class methods are prefixed with the class name. class Song @@plays = 0 ... def Song.numOfPlays @@plays end song.play print Song.numOfPlays # “2”

Classes : Access Control Difference from C++ and Java : “private” members are not available to other objects !!! class MyClass ... def method1 # default is public public # explicitly public def method2 protected def method3 # this class and subclasses private def method4 # this _object_ only end

Classes : Inheritance Single inheritance only. class KaraokeSong < Song attr_reader :lyrics def initialize( name, artist, duration, lyrics ) super( name, artist, duration ) @lyrics = lyrics end def play # overload the base class method super song = KaraokeSong.new( “Lullaby”, “Me”, 600.0, “It’s..” ) song.play # play the derived class’s method

Mixing Ruby replacement for multiple inheritance. Note, that “self” is the same as “this” in C++ module Debug def whoAmI? “#{self.type.name} : #{self.id}” end class MyClass include Debug # Include the contents of the module ... # as if all its constants and methods end # were defined by the current class. a = MyClass.new print a.whoAmI? # “MyClass : 1234567890”

Mixing : Comparison Operators An “almost free” way to bring a new functionality into a user-defined class. Just include a library module Comparable and provide the only method “” (“spaceship operator). class Song include Comparable # defines: <, >, <=, >=, ==, != ... def (other) self.duration  other.duration end c1 = Song.new( “Name1”, “Artist1”, 600.0 ) c2 = Song.new( “Name2”, “Artist2”, 555.5 ) if c1 < c2 then c1.play

Mixing : Iterators An “almost free” way to bring a full glory of iterators into a user-defined class. Just include a library module Enumerable and provide the only method “each”. class MyCollection include Enumerable private attr :collection # an array w/ elements def each for e in @collection yield e end c = MyCollection.new a = c.sort # get a sorted array of MyCollection’s # elements. e = c.find { |e| e.type.name == “Fixnum” }

Extending Class Definition Any (including predefined) classes can be extended at any time. This will affect all existing and new objects unless those objects Are “frozen”. array = [ “a”, “b”, “c”, “d” ] class Array def to_ids ids = [] each { |e| ids << e.id } ids end array.to_ids # [ 123456, 2345676, 23456, 233445 ] array.freeze unless array.frozen? # it’s stable now copiedArray = array.dup # get modifiable

Exceptions Exceptions are objects of Exception class or its subclasses. require “socket” socket = TCPSocket.open(‘www.mp3.com’, ‘port’) f = File.open(“OutFile.mp3”, “w”) begin while data = socket.read(512) f.write(data) end rescue SystemCallError print “IO failed: “ + $! f.close File.delete(“OutFile.mp3”) raise “IO failed” # produce RuntimeError exception

Exceptions : Complete Path f = File.open(“OutFile.mp3”, “w”) begin # process something rescue Exception1 # handle this particular exception rescue # handle other exceptions else # Congratulations! No errors. ensure # always gets executed. f.close unless f.nil? end

Threads & Processes They are available Threads (light weight processes) Subprocesses (fork, exec) Standard set of threads synchronization methods: Mutexes, Condition variables, Monitors, etc. Problems on Windows: Do not map onto NT native threads – the simulation is clearly not based on a preemptive scheduling mechanism.

Misc Extension to C is possible Lots of existing modules solving various problems Apache Web server module: mod_ryby Documentation and books available Stable releases Still under development Performance