Title: Young
1Young InterpretedPython, Ruby, JavaScript
- Susan Haynes
- 18 February 2008
2These 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 ---
its a duck. - Interpreted -- Source code is not compiled then
executed. Instead, the source is executed by the
interpreter - Released 92 - 95
3Theyre Really Different
- Extent of Object Orientation
- JavaScript is just barely OO
- Ruby is practically pure OO
- Python has extensive set of primitive sequential
structures. JavaScript has String and Array - JavaScript 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.
4Origins
- 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
5Questions
- Suitable for CS education?
- What are they good for?
- Coolness factor?
6What do I know?
- Not much. I havent 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).
7Demos
- JavaScript using browser -(
- Python using IDLE or shell (python file)
- Ruby using irb or shell
- (ruby file.rb)
8White 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.
9Line 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.
10Numbers
- 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
11Variable Names
- JavaScript -- the usual
- Python -- the usual
- Ruby --
- Local variables start with lower case or _
- Instance variables start with _at_
- Class variables start with _at__at_
- Globals start with
12Simple Python Program
Output enter integer 3 enter float -14.34 s1s2
3-14.34 n1n2 -11.34
First program first.py s1 raw_input(enter
integer ) s2 raw_input(enter float ) s3
s1 s2 print s1s2 s3 \n n1
int(s1) n2 float(s2) n3 n1n2 print n1n2
n3
Run this with Python and Idle import first then
reload(first) on subsequent changes
13Another simple Python program
Second program second.py x 10 y 3 print
type(x) , type(x) print type(y) ,
type(y) y int(y) print type(y) ,
type(y) dir()
Output import second type(x) int type(y) type(y) int __builtins__, __doc__,
__name__ first, n1, n2, sys, x, y
Notice use of type(), str() and dir() type(varX)
returns type of varX str(varY) any varY has a
nice string representation dir() lists all
known names
14Parallel Assignment
- Python, Ruby and JavaScript 1.7 have parallel
assignments. - Here is a python example (idle)
t (a, b, c) type(t) tuple t0 a t1 b type ( (x,
y, z) ) (x, y, z) t
x a y b
15Method Names
- JavaScript -- the usual
- Python -- the usual
- Ruby -- has a convention thats pretty neat
(youll 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
16Arrays
- 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
17Javascript - simple array
- // see array.html
- var arr1 2, 4, 6, 8, "who", "do", 'we',
"appreciate", "?" - document.write("Outputting initialized arr1
") - document.write(arr1)
- document.write("I'm slicing the arr1
- from index 2 to 3nd from end")
- arr2 arr1.slice(2, -2)
- document.write(arr2)
- document.write("I'm adding elements to arr1
- at index 20, 21")
- arr120 1, 2, 3
- arr121 "ta"
- document.write(arr1)
-
18Dictionary
- JavaScript Arrays can be Associate Arrays (like
property lists) - see assoc-array.html - arr1"dog" "mammal"
- arr1"parrot" "bird"
- arr1"tarantula" "arachnid"
- for (var i in arr1)
- document.write(arr1i " ")
- Python and Ruby use a different data structure
- Python next slide
19Dictionary
- 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', 'mammal'
- dict(10, "a")
- 42
20Composite 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 Javas ArrayList
- 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
21Defining 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
22Closures
- All three allow for some kind of closure (an
unnamed function) - Ruby example coming up later in looping
23Control 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).
24Event handling
- All offer event handling with variations in syntax
25Ruby expressiveness looping examples (1)
fitz56.rb initialize array values 1, 2,
"buckle", "my", "shoe" puts "\n--print array
using while" i 0 while i 'do' is optional here print valuesi, " " i
1 end puts "\n\n-- using 'do-while'" i0 begin
print valuesi, " " i 1 end while i values.size
26Ruby expressiveness looping examples (2)
puts "\n\n--print array using nameless
function" values.each do e print e, "
" end puts "\n\n--print array using nameless
function with " values.each e print e, " "
puts "\n\n--print array using for" for i in
0..values.size-1 do print valuesi, "
" end puts "\n\n--using Integer's upto
method" 0.upto(values.size-1) i print
valuesi, " "
27Creating 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.
28JavaScript class example defining
- // see objects.html
- function Horse (name)
- this.name name
- this.getName getHorseName
- this.setName setHorseName
-
-
- function getHorseName ()
- return this.name
-
- function setHorseName(name)
- this.name name
-
29JavaScript class example modifying
- Horse.prototype.gait "walk"
- function getHorseGait ()
- return this.gait
-
- function setHorseGait (gait)
- this.gait gait
-
- Horse.prototype.setGait setHorseGait
- Horse.prototype.getGait getHorseGait
30Ruby class example Defining
- fitz128.rb
- class Horse def initialize (name) execute
AFTER instantiation _at_name name instance
variable end def name getter _at_name
end last value is returned def name
(name) setter _at_name name endend
31Ruby class example modifying
- fitz128b.rb
- repeated code deleted
- class Horse
- def initialize ( name 'pokey', age 10)
- _at_name name
- _at_age age
- end
-
- def say_whoa
- puts "Whoa there " _at_name
- end
- end
32Python class example defining
Run in IDLE
- Class Doggie
- size 25
- friendly True
-
- def sayArf(self)
- print(arf)
- fifi Doggie()
- fifi.size
- fifi.sayArf()
33Ruby metaprogramming to make class definition
easier
- To irb
- class Horse
- attr gait, true
- attr name, true
- def say_whoa
- puts Whoa there _at_name
- end
- end
- Horse.instance_methods - Object.instance_methods
- h1 Horse.new
- h1.name pokey
- h1.gait trot
- p h1
34Python 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
type(fib) help(fib) help on
function fib in module __main__ fib(n)
calculate fibonacci number of parameter
fib(5) 120
35Python code Example 2 A couple stacks
p type(p)
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
36Python list mapping
li range(10) li 0, 1, 2, 3, 4, 5, 6,
7, 8, 9 li2 i2 for i in li li2 0,
2, 4, 6, 8, 10, 12, 14, 16, 18 li 0, 1, 2,
3, 4, 5, 6, 7, 8, 9
37Documentation
- JavaScript ?
- Python
- help( . . .) returns the docstring of the object
- Ruby
- ri, shell command
38At the end of the day
- Everyone should make a language
- Many similarities between JavaScript, Python and
Ruby - dynamic typing
- OO
- Single inheritance
- Flexible list lengths
- Interesting (useful) data types list, hash,
tuple, - Lambdas, closures
- Modifiable class definitions
39Which 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
40Which 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 JavaScripts
- 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.
41http//imgs.xkcd.com/comics/python.png
42Which is better? Ruby?
- OMG! If I were a CS senior, this is the language
I would code in. It is a programmers 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 peoples code is
already hard enough to read. - Development environment is not as strong as
Pythons. - 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
43Downloads?
- 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.
44Resources
- Javascript
- About a gazillion Web tutorials
- JavaScript Standard (OReilly book)
- Many, many, many crappy textbooks and how-to
books. Run away! - Python www.python.org
- Guidos 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 Fitzgeralds Learning Ruby
(OReilly). Very simple and readable.
45EOTQuestions?