7. Procs
● Basics of creating and using
Procs.
● Relationship between procs
and blocks.
● Procs as closures
● Proc parameters & arguments
@rabajaj_
8. Relationship between
procs and blocks.
def capture_block(&block)
block.call
end
capture_block { puts "Inside the block" }
Block to Proc
Using Procs for Blocks
def capture_block(&block)
block.call
end
p = Proc.new { puts “This proc arg will serve as code
block” }
capture_block(&p)
@rabajaj_
Inside the block
This proc arg will serve as code block
9. closures
def call_some_proc(pr)
a = “irrelevant ‘a’ in method scope”
puts a
pr.call
end
a = “ ‘a’ to be used in Proc block”
pr = Proc.new { puts a }
pr.call
call_some_proc(pr)
‘a’ to be used in Proc block
irrelevant ‘a’ in method scope
‘a’ to be used in Proc block
@rabajaj_
11. Lambdas
The lambda method returns a
Proc object!
● Basic creation of Lambda.
● Difference between Proc and
Lambda:
a. Calling
b. Return method
c. Arguments
@rabajaj_
15. Threads
continued..
t = Thread.new do
puts "Starting the thread"
sleep 1
puts "At the end of the thread"
end
puts "Outside the thread"
t.join
@rabajaj_
16. puts "Trying to read in some files..."
t = Thread.new do
(0..2).each do |n|
begin
File.open("part0#{n}") do |f|
text << f.readlines
end
rescue Errno::ENOENT
puts "Message from thread: Failed on n=#{n}"
Thread.exit
End
end
end
t.join
puts "Finished!"
@rabajaj_
Trying to read in some files...
Message from thread: Failed on n=1
Finished!
THREAD TERMINATION (KILLING)
The idea is to read the contents of the three
files (part00, part01, part02) into the string
text. If any of the files isn’t found, the thread
terminates.