Recall the creation of a 3x3 Array
# matrix.rb
a2d = Array.new(3){Array.new(3)}
{Array.new(3)} is a codeblock
Let's see what else we can do
# matrix.rb
a2d1 = Array.new(3){Hash.new()}
a2d2 = Array.new(3){|i| i}
# matrix.rb
a2d1 = Array.new(3){Hash.new()}
a2d2 = Array.new(3){|i| i}
Codeblock: segment of code that another method uses
Main idea: Code treated as data
How to call codeblock?
# codeblock.rb
def func1
if block_given?
yield
end
end
func1 {puts "hello"}
Codeblocks are like in-line functions
# the two are similar
{|i| y = i + 1; puts y}
def f(i) y = i+1; puts y end
Control is passed to codeblock like a function call
Control is passed to codeblock like a function call
" codeblock-1.rb
def func2
if block_given?
for i in 1..3
yield i
end
end
end
Can take arguments like a function call too
Procs make codeblocks into objects
# procs.rb
p = Proc.new {puts "hello"}
But have to be called, not yielded to
# procs-1.rb
def func3(p)
p.call
end
p = Proc.new {puts "hello"}
func3(p)
Can be strung together
# procs-2.rb
def say(y)
t = Proc.new {|x| Proc.new {|z| z+x+y }}
return t
end
s = say(2).call(3)
puts s.call(4)
Important: Codeblocks and Procs are not the same
Higher Order Programming: Programming that uses functions as data
Higher Order Function: A function that takes in a function as data
Mostly seen in functional programming langauges
Here is a sneak peek
let f1 f x = f (x) in f1 (fun x -> x + 2) 12