Code Blocks, Closures, and ContinuationsPresented by: Bassem ELkarablieh
Outline Getting Started with ruby Some ruby syntax Ruby classes More ruby syntax New concepts in ruby
Getting Started Ruby is a dynamic, fully object-oriented scripting language. Installing ruby:
http://www.ruby-lang.org One click windows installation (takes 5 min to setup ruby)
Running ruby Interactive ruby (irb) Batch ruby (run program files)
Getting Started Ruby documentation
http://www.ruby-doc.org Using the ri tool
What did we learn
Some ruby Syntax Ruby is fully OO
Every thing is an object (even literals) “hello”.length “bassem”.index(“e”) -88.abs
Variable definition Number = 5 Number = “5” Number = “five”
Delimiters: no ending ”;” is required
Some ruby Syntax Simple I/O
Puts: write the value to the output with new line character appended
Gets: reads the value from standard input A = gets puts “Hello I am “ + A
Conditions If else blocks
If A>8 puts “greater”
Else Puts “smaller”
end
Some ruby Syntax Looping
While block While line = gets
Puts line.uppercase End
For … In blocks For I in 1..7
Print I, “ “ Control structures
Break, redo, next , retry
Some ruby Syntax Assignment
a = b = 1+2+3 Instrument = “piano” Instrument [“ano”] = “ccolo”
Parallel Assignment a,b = 6,7
Method definition def my_method(arg1,arg2,arg3)
#this is a comment and code Def
What did we learn
Classes in Ruby Initializer Instance variable Class variables Instance methods Class methods Attributes operators Access controls
Classes in ruby Demo of a class
More ruby syntax Containers Code blocks Iterators
Containers Arrays
A= [56,”hello”,99.66,”ll”] B=Array.new Un-initialized members of an array are set to nil
Indexing an array A[0] ->56 , A[-1] =“ll” A[1,1] ->[“hello”] A[0..2]-> [56,”hello”,99.66]
Containers Hashes H ={‘dog’=>’canine’, ‘cat’ => ’feline’, ’bird’ => ‘duck’} H.length => 3, h[‘dog’] =>’canine’ H[12] = ‘hello’, H[‘cat’] =99
Code Blocks Chucks of code that can be associated with method invocations Great methods for implementing callbacks Great tool for implementing iterators Code blocks are flexible , and can be passed parameters Great tool for implementing closures and continuations
Code Blocks Code block can be stored between{} or between do…end blocksDef my_methodputs “hello”yieldyieldEndmy_method{puts “world”} Code block parameters differ from method parametersDef say_goodnight(name)puts “good night, #{name}”Yield (“sweet dreams”)EndSay_goodnight(“bassem”){|i| print i}
Iterators Built in iterators in ruby uses code block to support general plug-in architecture Examples
5.times{print “*”} 3.upto(6) {|i| print i} (‘a’..’z’).each{|char| print char} [‘cat’,’dog’,’horse’].each{|name| print name} [1,3,5,7,9].find{|v| v*v>3} [“H”,”A”,”L”].collect{|x| x.succ} [1,3,5,7].inject(0){|sum,element| sum+element}
New concepts in ruby Closures Continuations Dynamic manipulations
Closures A closure is a function created by a
program at run time. This idea is written as a function that appears entirely within the body of another function. The nested, inner function may refer to local variables of the outer function.
A closure can be used to represent a delayed user defined behavior that can be passed around in methods and objects
Closures Closure simulations
C: function pointers, void* parameters C++: Functors C# and java: Anonymous classes and methods
Ruby have a special built-in Proc class that simplifies implementing closures
Proc Class Proc objects are blocks of code that have been bound to a set of local variables, once bound the code can be called from different context. Example:Def gen_times(factor)return Proc.new{|n| n*factor}EndTimes3 = gen_times(3)Times5 = gen_times(5)
Times3.call(12)Times5.call(3)Times3.call(times5.call(4))
Proc Objects Proc objects can be created by associating a code block with it Example
Def proc_fromProc.new
EndProc = proc_from{“hello”}Proc.call
Code blocks as closures Example1
Def n_times (thing)Return lambda {|n| thing*n}
End# here lambda returns a Proc object associated with the code block P1 = n_times(23)P1.call(3)P2 = n_times(“hello”)P2.call(4)
Code blocks as closures Example2Songlist = SongList.newClass JukeboxButton<ButtonDef initialize(label,&action)Super(label)@action = actionEndDef [email protected](self)EndEnd Start_button = JukeboxButton.new(“start”){songlist.start}pause_button = JukeboxButton.new(“pause”){songlist.pause}
Continuations Continuations are objects that lets
you save system state, and then return to that state on command
Code blocks defines the universe in a continuation
Continuations A continuation object saves the execution state( mainly the execution stack) A continuation is created using a call to a Kernel method “callcc” which associates a continuation to a code block Similar to Proc object , continuations are triggered using a “call” method
Callcc method Generates a continuation object , which it passes to the associated block Performing a cont.call will use the callcc to return The value returned by callcc is the value of the block or the value passed to cont.call
Continuations Example1Calloc do|cont|For i in 0..4print “\n#{i}:”for j in i*5 … (i+1)*5cont.call() if (j==7)print jendEndEnd
Continuation Objects Callcc return values implicitly
Callcc{|cont| cont.call}Callcc{|cont| cont.call 1}Callcc{|cont| cont.call 1,2,3}
Callcc return values Explicitly Callcc{|cont| return cont}
Continuations Example2Def strangecalloc {|cont| return cont}print “back to method”EndPrint “before method”Temp = strange()Print “after method”If( Temp) Temp.call
Continuations Example3
1. Def loop2. for i in 1..53. puts I4. callcc{|cont| return cont} if i==25. end6. return nil7. End8. Puts “before loop”9. Temp = loop()10. Puts “after loop call”11. If( Temp) Temp.call12. Puts “after continuation call”
Done Final demo
Any Questions
What's next in ruby Ruby types Ruby methods Ruby Expressions