Lecture Notes for CS142
Winter Quarter 2009
John Ousterhout
sum = 0 i = 1 while i <= 10 do sum += i*i i = i + 1 end puts "Sum of squares is #{sum}\n"
x = Array.new y = ["Alice", 23, 7.3]
x = Hash.new y = {"name" => "Alice", "age" => 23}
if x < 10 then ... elsif x < 20 ... else ... end while x < 10 do ... end array = [14, 22, 34, 46, 92] for value in array do ... end
[1, 2, 3, 4].each do |x| print x + "\n" end
def oddNumbers(count) number = 1 while count > 0 do yield(number) number += 2 count -= 1 end end oddNumbers(5) do |i| print(i, "\n") end
def fac(x) if x <= 0 then return 1 end return x*fac(x-1) end
puts "Hello world" f (3+2)+1
def inc(value, amount=1) value+amount end
def max(first, *rest) max = first rest.each do |x| if (x > max) then max = x end end return max end
def create_widget(size, properties) ... end create_widget(6, {:name => "Alice", :age => 31}) create_widget(6, :name => "Alice", :age => 31)
class Point def initialize(x, y) @x = x @y = y end def x @x end def x=(value) @x = value end end p = Point.new(3,4) p.x => 3 p.x = 44;
class MyClass include Enumerable ... def each ... end end