Ruby expressiveness: looping examples

Download Report

Transcript Ruby expressiveness: looping examples

Young & Interpreted:
Python, Ruby, JavaScript
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
 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.
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
 JavaScript 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
 JavaScript -- 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
s1 = raw_input(“enter integer: “)
s2 = raw_input(“enter float: “)
s3 = s1 + s2
print “s1+s2 “ + s3 + “\n”
n1 = int(s1)
n2 = float(s2)
n3 = n1+n2
print “n1+n2: “ + n3
n1+n2 -11.34
enter integer: 3
enter float: -14.34
s1+s2 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’, ‘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
Parallel Assignment
Python, Ruby and JavaScript 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
 JavaScript -- 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 arr1 = [2, 4, 6, 8, "who", "do", 'we', "appreciate", "?" ];
document.write("<h2>Outputting initialized arr1 “ +
“</h2>");
document.write(arr1);
document.write("<h2>I'm slicing the arr1 “ +
“from index 2 to 3nd from end</h2>");
arr2 = arr1.slice(2, -2);
document.write(arr2);
document.write("<h2>I'm adding elements to arr1 “ +
at index 20, 21</h2>");
arr1[20] = [1, 2, 3];
arr1[21] = "ta";
document.write(arr1);
Dictionary
 JavaScript Arrays can be Associate
Arrays (like property lists) - see assocarray.html
arr1["dog"] = "mammal";
arr1["parrot"] = "bird";
arr1["tarantula"] = "arachnid";
for (var i in arr1)
document.write(arr1[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', '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 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 }
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)
# fitz56.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 "\n\n--> using 'do-while'"
i=0
begin
print values[i], " "
i += 1
end while i < values.size
Ruby 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 values[i], " "
end
puts "\n\n-->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.
JavaScript 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
}
JavaScript 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;
Ruby class example:
Defining
# fitz128.rb
class Horse
def initialize (name)
@name = name
end
def name
@name
end
def name= (name)
@name = name
end
end
# execute AFTER instantiation
# instance variable
# getter
# last value is returned
# setter
Ruby class example:
modifying
#fitz128b.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
end
Python class
example: defining
Run in IDLE
Class Doggie:
size = 25
friendly = True
def sayArf(self):
print(“arf”)
fifi = Doggie()
fifi.size
fifi.sayArf()
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
end
Horse.instance_methods - Object.instance_methods
h1 = Horse.new
h1.name= “pokey”
h1.gait = “trot”
p h1
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 0xc3d3b0>
>>> 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,
>>>
>>>
[0,
>>>
[0,
li = range(10)
li
1, 2, 3, 4, 5, 6, 7, 8, 9]
li2 = [i*2 for i in li]
li2
2, 4, 6, 8, 10, 12, 14, 16, 18]
li
1, 2, 3, 4, 5, 6, 7, 8, 9]
Documentation
 JavaScript ?
 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 JavaScript,
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 ‘oldschool’ 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 JavaScript’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
 JavaScript Standard (O’Reilly book)
 Many, 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?