Young Interpreted Python Ruby Java Script Susan Haynes
Young & Interpreted: Python, Ruby, Java. Script Susan Haynes 18 February 2008
These three languages have a lot in common: § Dynamic typing -- variables have type, but the type can change during the course of execution § Implicit typing -- if it walks like a duck, quacks like a duck, and swims like a duck ---> it’s a duck. § Interpreted -- Source code is not compiled then executed. Instead, the source is executed by the interpreter § Released ‘ 92 - ‘ 95
They’re Really Different § Extent of Object Orientation § Java. Script is just barely OO § Ruby is practically pure OO § Python has extensive set of primitive sequential structures. Java. Script has String and Array § Java. Script is intended to run in web pages and is integrated with the DOM § Python and Ruby have lots of support for Web apps beyond displaying pages.
Origins § ruby released '95, author Yukihiro Matsumoto, open source § python released '91, author Guido van Rossum, open source § javascript released with Netscape ‘ 95. Originally developed by Brendan Eich (netscape) under the name ‘mocha’
Questions § Suitable for CS education? § What are they good for? § Coolness factor?
What do I know? § Not much. I haven’t done serious development in any of these languages -only toy stuff. § Plenty of experience learning a little bit about a lot of languages: PL/1, Algol, Pascal, Fortran, basic, Lisp, C, C++, Java, Ada, Prolog, APL, Javascript, various assemblers, scheme (squeak).
Demos § Java. Script using browser : -( § Python using IDLE or shell (python file) § Ruby using irb or shell (ruby file. rb)
White Space § Javascript does not care about whitespace. EXCEPT! Multiple statements on a single line must be separated by ‘; ’ § Python uses white space to indicate nesting level. § Ruby allows you to delete certain keywords depending on whitespace.
Line termination § Javascript ‘; ’ is optional except when multiple statement per line (but everyone uses it) § Python ‘; ’ is optional. No one uses it § Ruby ‘; ’ is optional. No one uses it.
Numbers § Javascript number is a fundamental type (along with String, boolean and Object) § Python number is a fundamental type, along with boolean, and various list types § Ruby number is an object: 3. zero? ==> returns false 3. kind_of? Integer==> returns true 3. class ==> return Fixnum 3. to_f ==> returns 3. 0
Variable Names § Java. Script -- the usual § Python -- the usual § Ruby -§ § Local variables start with lower case or _ Instance variables start with @ Class variables start with @@ Globals start with $
Simple Python Program First program: first. py Output s 1 = raw_input(“enter integer: “) s 2 = raw_input(“enter float: “) s 3 = s 1 + s 2 print “s 1+s 2 “ + s 3 + “n” n 1 = int(s 1) n 2 = float(s 2) n 3 = n 1+n 2 print “n 1+n 2: “ + n 3 n 1+n 2 -11. 34 enter integer: 3 enter float: -14. 34 s 1+s 2 3 -14. 34 Run this with Python and Idle import first then reload(first) on subsequent changes
Another simple Python program Second program: second. py Output x = 10 y = ‘ 3’ print “type(x): “ , type(x) print “type(y): “, type(y) y = int(y) print “type(y): “, type(y) dir() >>> import second type(x): <type ‘int’> type(y): <type ‘str’> type(y): <type ‘int’> [__builtins__’, ‘__doc__’, ‘__name’__’ ‘first’, ‘n 1’, ‘n 2’, ‘sys’, ‘x’, ‘y’ ] Notice use of type(), str() and dir() type(var. X): returns type of var. X str(var. Y): any var. Y has a “nice” string representation dir(): lists all known names
Parallel Assignment Python, Ruby and Java. Script 1. 7 have parallel assignments. Here is a python example (idle) >>> t = (‘a’, ‘b’, ‘c’) >>> type(t) <type ‘tuple’> >>> t[0] ‘a’ >>> t[1] ‘b’ >>> type ( (x, y, z) ) <type ‘tuple’> >>> (x, y, z) = t >>> x ‘a’ >>> y ‘b’
Method Names § Java. Script -- the usual § Python -- the usual § Ruby -- has a convention that’s pretty neat (you’ll see an example later) § Ending in ? , returns true or false § Ending in !, “in place” modifier of the object itself § Ending in =, a ‘setter’ of an instance variable
Arrays § Arrays can change size dynamically. § Elements can be of different types § Can do the standard indexing and slicing operations. § Javascript example (next slide) § All three let you use negative indexes to offset from the end
Javascript - simple array // see array. html var arr 1 = [2, 4, 6, 8, "who", "do", 'we', "appreciate", "? " ]; document. write("<h 2>Outputting initialized arr 1 “ + “</h 2>"); document. write(arr 1); document. write("<h 2>I'm slicing the arr 1 “ + “from index 2 to 3 nd from end</h 2>"); arr 2 = arr 1. slice(2, -2); document. write(arr 2); document. write("<h 2>I'm adding elements to arr 1 “ + at index 20, 21</h 2>"); arr 1[20] = [1, 2, 3]; arr 1[21] = "ta"; document. write(arr 1);
Dictionary § Java. Script Arrays can be Associate Arrays (like property lists) - see assoc-array. html arr 1["dog"] = "mammal"; arr 1["parrot"] = "bird"; arr 1["tarantula"] = "arachnid"; for (var i in arr 1) document. write(arr 1[i] + " "); § Python and Ruby use a different data structure § Python: next slide
Dictionary § Python example (from idle) >>> dict = {"dog": "mammal", "cat": "mammal", (10, 'a'): 42} >>> dict {(10, 'a'): 42, 'dog': 'mammal', 'cat': 'mammal'} >>> str(dict) "{(10, 'a'): 42, 'dog': 'mammal', 'cat': 'mammal'}" >>> dict. keys() [(10, 'a'), 'dog', 'cat'] >>> dict. values() [42, 'mammal'] >>> dict[(10, "a")] 42
Composite types Summary for Python Each type has many useful methods; indexing and slicing are essentially the same for all types § § § String, immutable, a sequence of character: “this is a string” § String delimiters are: ‘ ‘, “ “, “”” List, mutable, a sequence of anything: ( 3, 4, “abc”) Array, similar to Java’s Array. List: § [‘this’, 1, -4. 2, [4, “abc”] ] § § Can insert and delete to a list. Many methods available: § y = []. append(“twenty”) #y has value [‘twenty’] Tuple, an immutable set of items § (“smith”, “jane”, 24000, “ 123 -45 -6789”) § Dictionary, a property list or hash table. The key is immutable § {(“smith”, “jane”, 24000, “ 123 -45 -6789”): 4, “vehicle”: “truck”, age: 19 }
Defining Methods § Javascript and Python have an explicit return statement, that may be ignored by the caller § Ruby always returns the last value computed (may be ignored by caller) § All allow for variable argument lists § Python allows for naming parameters
Closures § All three allow for some kind of closure (an unnamed function) § Ruby example coming up later in looping
Control Structures § The usual suspects with differences in syntax: IF, Looping (while, for, etc), Switch, break, continue. § Ruby is a little richer with unless (opposite of if) and until (opposite of while).
Event handling All offer event handling with variations in syntax
Ruby expressiveness: looping examples (1) # fitz 56. rb #initialize array values = [1, 2, "buckle", "my", "shoe"] puts "n-->print array using while" i=0 while i < values. size do # 'do' is optional here print values[i], " " i += 1 end puts "nn--> using 'do-while'" i=0 begin print values[i], " " i += 1 end while i < values. size
Ruby expressiveness: looping examples (2) puts "nn-->print array using nameless function" values. each do |e| print e, " " end puts "nn-->print array using nameless function with {}" values. each { |e| print e, " " } puts "nn-->print array using for" for i in 0. . values. size-1 do print values[i], " " end puts "nn-->using Integer's upto method" 0. upto(values. size-1) { |i| print values[i], " " }
Creating classes - Many similarities § Class definitions are open, so instance variables and members can be added later, methods can be overridden by adding the new definition. § Single inheritance. Object is the base class.
Java. Script class example: defining // see objects. html function Horse (name) { this. name = name; this. get. Name = get. Horse. Name; this. set. Name = set. Horse. Name; } function get. Horse. Name () { return this. name; } function set. Horse. Name(name) { this. name = name }
Java. Script class example: modifying Horse. prototype. gait = "walk"; function get. Horse. Gait () { return this. gait; } function set. Horse. Gait (gait) { this. gait = gait; } Horse. prototype. set. Gait = set. Horse. Gait; Horse. prototype. get. Gait = get. Horse. Gait;
Ruby class example: Defining # fitz 128. rb class Horse def initialize (name) @name = name end def name @name end def name= (name) @name = name end # execute AFTER instantiation # instance variable # getter # last value is returned # setter
Ruby class example: modifying #fitz 128 b. rb # repeated code deleted class Horse def initialize ( name = 'pokey', age = 10) @name = name @age = age end def say_whoa puts "Whoa there " + @name end
Python class example: defining Run in IDLE Class Doggie: size = 25 friendly = True def say. Arf(self): print(“arf”) fifi = Doggie() fifi. size fifi. say. Arf()
Ruby: metaprogramming to make class definition easier To irb class Horse attr : gait, true attr : name, true def say_whoa puts “Whoa there “ + @name end Horse. instance_methods - Object. instance_methods h 1 = Horse. new h 1. name= “pokey” h 1. gait = “trot” p h 1
Python code Example 1: defining a function >>> def fib(n): “”” Calculate fibonacci Number of parameter “”” if n < 1: return 1 else: return n * fib(n-1) >>> fib <function fib at 0 xc 3 d 3 b 0> >>> type(fib) <type ‘function’> >>> help(fib) help on function fib in module __main__: fib(n) calculate fibonacci number of parameter >>> fib(5) 120
Python code Example 2: A couple stacks >>> p = [] >>> type(p) <type ‘list’> >>> p. append(1) >>> p. append(2) >>> p. append(“buckle”) >>> p. append(“my”) >>> p. append(5) >>> p {1, 2, ‘buckle’, ‘my’, 5] >>> q = [] >>> while p: q. append(p. pop()) >>> p [] >>> q [5, ‘my’, ‘buckle’, 2, 1]
Python list mapping >>> >>> [0, li = range(10) li 1, 2, 3, 4, 5, 6, 7, 8, 9] li 2 = [i*2 for i in li] li 2 2, 4, 6, 8, 10, 12, 14, 16, 18] li 1, 2, 3, 4, 5, 6, 7, 8, 9]
Documentation § Java. Script ? § Python § help(. . . ) returns the docstring of the object § Ruby § ri, shell command
At the end of the day § Everyone should make a language § Many similarities between Java. Script, Python and Ruby: § § § § dynamic typing OO Single inheritance Flexible list lengths Interesting (useful) data types: list, hash, tuple, … Lambdas, closures Modifiable class definitions
Which is better? Javascript? § Javascript feels kind of klugey -- especially in its OO support, but also in some other things (e. g. the same variable can hold an indexed array and a dictionary) § Javascript is quite accessible, especially to ‘old-school’ computer profs who learned to program in a procedural language. § The close connection with client-side programming has affected the typical development environment in unpleasant ways (because, mostly, of non-standard compliant browsers). § Debugging support is not good. § Still the go-to language for dynamic web pages § There are lots of Javascript libraries out there. You have to find what you want and include it with <script type=“text/javascript” src=“library. js” />
Which is better? Python? § Easy learning curve for the initial bit. § Great for quick development § Very readable code, thanks to the indent rule and other syntax rules § OO is pretty good -- cleaner than Java. Script’s § Lovely set of data types § My opinion: I found the syntax very natural § Code is not too terse: good for noobs to read & write. § Import is easy § Very easy to get information from interpreter § Really nice debugging support, both in terms of debugger and in terms of online help § I had an easier time moving between the IDE and the shell with Python than with Ruby § Terrific community and support.
http: //imgs. xkcd. com/comics/python. png
Which is better? Ruby? § OMG! If I were a CS senior, this is the language I would code in. It is a programmer’s language. Like perl (with a scheme-feel for OO, and some lisp thrown in) but with a lot more stuff and slightly more disciplined. § Very pristine OO framework. § Very easy to get information from interpreter -- most powerful support for reflection. § As a teacher, no way! Other people’s code is already hard enough to read. § Development environment is not as strong as Python’s. § An enthusiastic and growing fan-base. § POLS, principle of least surprise (the language should minimize confusion for experienced users). § Ruby-on-Rails is reputed to be a “killer app”
Downloads? § Javascript is typically available with a browser. Develop in a plain text editor and execute in the browser. § Python and Ruby both “come with” Linux/Unix distributions -- so hurrah for OSX. § Python and Ruby interpreters have been implemented for assorted platforms, including Windows.
Resources § Javascript § About a gazillion Web tutorials § Java. Script Standard (O’Reilly book) § Many, many crappy textbooks and how-to books. Run away! § Python www. python. org § Guido’s tutorial is very good. § The online book, Dive into Python is good for programmers § Python for Dummies. 2 stars. § Ruby www. ruby-lang. org § There are some tutorials there. Not bad. § I can recommend Fitzgerald’s Learning Ruby (O’Reilly). Very simple and readable.
EOT Questions?
- Slides: 45