

x = 1 x = "1" # x can hold an int or a string
def quack(x) # no parameter type
print(x + x + x)
end
quack("q") # qqq
quack(2) # 6
quack(true) # error: no + for boolean
[1, 2, 3].each { |a| print 2 * a, " " } # prints 2 4 6
yield
def filter(a)
r = []
for i in a
if yield(i) then r.push(i) end # invoke block
end
return r
end
filter([1,4,9,16,25]) { |x| x % 2 == 0 } # returns [4,16]
def double(x) return 2*x end double(2) # returns 4 double 2 # also ok, no () def average(x,y) 0.5*(x + y) end # last expression is returned average 2,4
print("Hello", :size=>18, :style=>:italic, :weight=>:bold, :face=>"Courier")
Function receives a map of all => pairs
def print(str, params = {}) # params is empty map if no args supplied
if !params[:size].nil? then ... end
...
end
:size is a symbol, a unique string (called
atom in Lisp)
@attr_accessor adds fields and getters/settersinitialize
class Tree
attr_accessor :children, :name
def initialize(name, children = [])
@name=name
@children=children
end
def visit(&block) # & captures otherwise anonymous block
block.call(self) # self is implicit parameter ("this" in C++/Java)
children.each { |c| c.visit(&block) }
end
end
t = Tree.new("Cay", [Tree.new("Charlotte"), Tree.new("Emily")])
t.visit { |n| puts(n.name) }
class Object
def quack
print(self + self + self)
end
end
2.quack # prints 6
"q".quack # prints qqq
2.class.quack # error: undefined method `+' for Fixnum:Class

sudo apt-get rubysudo port install rubyapt-cyg install rubyirb.a. How did you do that?quack function on all elements of the array, using a
block. How did you do that?map that applies a
block to all elements of an array and returns an array of the results. For
example,
map([1,2,3]) { |x| x * x }
should return
[1,4,9]
Hint: Adapt the filter function
What is the code of your function?
:sorted and :descending
(true or false). For example,
map([1,3,2], :descending => true) { |x| x * x }
returns the mapped values in the opposite order:
[4,9,1]
120
/ \
10 12
/ \ / | \
2 5 2 2 3
How do you do that?
(120 (10 (2) (5)) (12 (2) (2) (3)))
How do you do add this to the tree class (without changing the original class)?