Download MTAT.03.295

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
MTAT.03.295
Agile Software
Development in the Cloud
Lecture 3: More on Ruby
Luciano García-Bañuelos
University of Tartu
Blocks
class Array!
def iterate!!
self.each_with_index do |n, i|!
self[i] = yield(n)!
end!
end!
end!
!
array = [1, 2, 3, 4]!
!
array.iterate! do |n|!
n ** 2!
end!
!
puts array.inspect!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS Blocks => Procs
class Array!
def iterate!(&code)!
self.each_with_index do |n, i|!
self[i] = code.call(n)!
end!
end!
end!
!
array = [1, 2, 3, 4]!
!
array.iterate! do |n|!
n ** 2!
end!
!
puts array.inspect!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS Procs … can be reused!
class Array!
def iterate!(code)!
self.each_with_index do |n, i|!
self[i] = code.call(n)!
end!
end!
end!
!
array_1 = [1, 2, 3, 4]!
array_2 = [2, 3, 4, 5]!
!
square = Proc.new {|n| n ** 2}!
!
array_1.iterate!(square)!
array_2.iterate!(square)!
!
puts array_1.inspect!
puts array_2.inspect!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS Lambdas
class Array!
def iterate!(code)!
self.each_with_index do |n, i|!
self[i] = code.call(n)!
end!
end!
end!
!
array = [1, 2, 3, 4]!
!
array.iterate!( lambda { |n| n ** 2 })!
!
puts array.inspect!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS Lambdas … strictly check
number of parameters
def args(code)!
one, two = 1, 2!
code.call(one, two)!
end!
!
args(Proc.new{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}"})!
!
args(lambda{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}"})!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS Lambdas … perform
“diminutive returns”
def proc_return!
Proc.new { return "Proc.new"}.call!
return "proc_return method finished"!
end!
!
def lambda_return!
lambda { return "lambda" }.call!
return "lambda_return method finished"!
end!
!
puts proc_return!
puts lambda_return!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS Classes and Mixins
module Persistence!
def load sFileName!
puts ”Reading ‘#{sFileName}’ contents into 'my_data'"!
end!
def save sFileName!
puts "Persisting '#{@my_data}' into '#{sFileName}'"!
end!
!
end!
!
class MyClass!
include Persistence!
attr :my_data!
!
def data=(someData)!
@my_data = someData!
end!
end!
!
b = MyClass.new!
b.data = "This_15_my_pwd"!
b.save("passwords")!
b.load("passwords")!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS Finally … metaprogramming
class Polyglot!
@@greetings = {estonian: "Tere hommikust", english: "Good morning"}!
!
def Polyglot.add_language(language, greeting)!
@@greetings[language] = greeting if language.is_a? Symbol!
end!
!
def method_missing(name)!
unless @@greetings[name].nil?!
puts @@greetings[name]!
else!
super!
end!
end!
end!
!
a = Polyglot.new!
!
a.estonian!
a.english!
RUBY LUCIANO GARCÍA-­‐BAÑUELOS 
Related documents