SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Downloaden Sie, um offline zu lesen
@autonomous
chris.spring@gmail.com
Going steady with
Ruby
1. {}, proc{}, ->{}
2. meta programming
3. modules
1) blocks,!
procs and!
lambdas
(1..3).each do |i|
puts i
end
# => 1
# => 2
# => 3
(1..3).each{ |i| puts i }
(1..3).each do |i|
puts i
end
# => 1
# => 2
# => 3
(1..3).each{ |i| puts i }
def each
for i in collection
yield i
end
end
def some_method(*arguments)
# ... pre conditions
yield( some_result )
# ... post conditions
end
def some_method(*arguments, &block)
# ... pre conditions
block.call( some_result )
# ... post conditions
end
file = File.new('credit_cards.txt', 'w')
file.puts 'XXXX XXXX XXXX 5534'
file.close
File.new('credit_cards.txt', 'w') do |file|
file.puts 'XXXX XXXX XXXX 5534'
end
Vs.
proc{} vs lambda{}
p = proc{ |i| puts "proc #{i}" }
p.call("hey!")
# => proc hey!
!
!
!
!
l = lambda{ |i| puts "lamb #{i}" }
l.call('yo!')
# => lamb yo!
p = proc{ |i| puts "proc #{i}" }
l = lambda{ |i| puts "lamb #{i}" }
!
(1..3).each(&p)
# => proc 1
# => proc 2
# => proc 3
!
(1..3).each(&l)
# => lamb 1
# => lamb 2
# => lamb 3
def do_something(a_p, b_l, &block)
print a_p.call()
print block.call()
print b_l.call()
end
!
!
p = proc{ "I'm a " }
l = lambda{ " and I'm ok!" }
!
!
do_something(p, l){ "lumberjack" }
# => I'm a lumberjack and I'm ok!
p.class
# => Proc
p.inspect
# => “#<Proc:0x0000010194d8b8@(irb):97>"
!
!
l.class
# => Proc
l.inspect
# => "#<Proc:0x0000010190cd68@(irb):98 (lambda)>"
p = proc{|i| puts i}
p.call()
# => nil
!
p.call(1)
# => 1
!
p.call(1, 2, 3)
# => 1
l = lambda{|i| puts i}
l.call()
# ArgumentError: wrong number of arguments
(0 for 1)
!
l.call(1)
# => 1
!
l.call(1, 2, 3)
# ArgumentError: wrong number of arguments
(3 for 1)
def proc_return
p = proc{ return ‘Never ' }
p.call
'Always '
end
!
!
def lambda_return
l = lambda{ return 'eat your vegetables!'}
l.call
'give up!'
end
!
!
"#{proc_return} #{lambda_return}"
Never give up!
2) META PROGRAMMING!
send :<3
class Statistics
def initialize(account)
@account = account
end
!
def increment_counts(metric, by=1)
case metric
when :sent
@account.increment_sent_count(by)
when :viewed
@account.increment_viewed_count(by)
when :bounced
@account.increment_bounced_count(by)
end
end
end
class Statistics
def initialize(account)
@account = account
end
!
def increment_counts(metric, by=1)
method = "increment_#{metric}_count"
@account.send(method, by)
end
end
class Account
# ...
private
def schedule_billing
# ...
end
end
!
class BillingRunner
def initialize(account)
@account
end
!
def run!
# ...
@account.send(:schedule_billing)
# ...
end
end
class Account
# ...
private
def schedule_billing
# ...
end
end
!
class BillingRunner
def initialize(account)
@account
end
!
def run!
# ...
@account.send(:schedule_billing)
# ...
end
end
define_method :awesome {}
class User
def admin!
@role = :admin
end
!
def admin?
@role == :admin
end
!
def client!
@role = :client
end
!
def client?
@role == :client
end
end
class User
ROLES = %i(admin client)
!
ROLES.each do |role|
define_method "#{role}?" do
@role == role
end
!
define_method "#{role}!" do
@role = role
end
end
end
%i(admin client supervisor technician vendor manager)
method_missing m, *args, &b
class KeyValueStore
def initialize(store={})
@store = store
end
!
def insert(key, value)
@store[key] = value
end
end
!
store = KeyValueStore.new
store.respond_to?(:insert)
# => true
!
store.insert(:one, 1)
!
m = store.method(:insert)
m.call(:two, 2)
!
store.instance_variable_get('@store')
# => {one: 1, two: 2}
class KeyValueStore
def initialize(store={})
@store = store
end
!
def insert(key, value)
@store[key] = value
end
end
!
store = KeyValueStore.new
store.respond_to?(:insert)
# => true
!
store.insert(:one, 1)
!
m = store.method(:insert)
m.call(:two, 2)
!
store.instance_variable_get('@store')
# => {one: 1, two: 2}
class KeyValueStore
# ...
!
def method_missing(method_name, *args, &block)
if @store.respond_to?(method_name)
@store.send(method_name, *args, &block)
else
super
end
end
!
def respond_to_missing?(method_name, include_private)
@store.respond_to?(method_name) || super
end
end
kv = KeyValueStore.new
kv.insert(:three, 3)
!
kv.respond_to?(:include?) # => true
kv.include?(:three) # => true
!
m = kv.method(:include?)
m.call(:four) # => false
!
kv.keys # => [:three]
kv.values # => [3]
3) Modules
module Mathematics
class Plane
# ...
end
end
!
!
module Airport
class Plane
# ...
end
end
module TehForce
def sense
'... a disturbance in the force'
end
end
!
class Person
include TehForce
# ...
end
!
p = Person.new
p.sense
# => "... a disturbance in the force"
Person = Class.new()
p = Person.new
!
!
p.sense
# NoMethodError: undefined method `sense' …
!
!
p.extend TehForce
p.sense
# => "... a disturbance in the force"
module UserDianostics
def perform_diagnostics
check_counts
validate_dates
find_orphans
end
!
# ....
end
!
user = User.find(some_id)
user.extend UserDianostics
user.perform_diagnostics
module RepublicPersonnel
def storm_trooper
Person.new
end
end
!
!
class CloningVat
extend RepublicPersonnel
end
!
!
CloningVat.storm_trooper
# => #<Person:0x0000010187c150>
Person = Class.new()
CloningVat = Class.new()
!
!
CloningVat.storm_trooper
# => NoMethodError: undefined method
`storm_trooper' …
!
!
CloningVat.extend RepublicPersonnel
CloningVat.storm_trooper
# => #<Person:0x0000010187c150>
include and extend?
module SomeMixin
module ClassMethods
# ...
end
module InstanceMethods
# ...
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
A contrived example…
admin = Administrator.new
admin.allowed_to_toggle_alarm? # => true
admin.allowed_to_visit_facebook? # => false
!
lacky = Lacky.new
lacky.allowed_to_be_seen? # => true
lacky.allowed_to_be_heard? # => false
lacky.allowed_to_make_eye_contact? # => false
class Administrator
include Permissions
!
can :toggle_alarm
end
!
admin = Administrator.new
admin.allowed_to_toggle_alarm? # => true
admin.allowed_to_visit_facebook? # => false
class Lacky
include Permissions
!
can :be_seen
end
!
lacky = Lacky.new
lacky.allowed_to_be_seen? # => true
lacky.allowed_to_be_heard? # => false
module Permissions
module ClassMethods
def can(do_something)
define_method "allowed_to_#{do_something}?" do
true
end
end
end
!
module InstanceMethods
def method_missing(*args, &block)
method_name = args[0]
if method_name && method_name =~ /allowed_to_.*?/
false
else
super
end
end
end
!
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
Thanks for
Listening
Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Implementações paralelas
Implementações paralelasImplementações paralelas
Implementações paralelas
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
 
Promises generatorscallbacks
Promises generatorscallbacksPromises generatorscallbacks
Promises generatorscallbacks
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
Tame cloud complexity with F# powered DSLs (build stuff)
Tame cloud complexity with F# powered DSLs (build stuff)Tame cloud complexity with F# powered DSLs (build stuff)
Tame cloud complexity with F# powered DSLs (build stuff)
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
VIM for (PHP) Programmers
VIM for (PHP) ProgrammersVIM for (PHP) Programmers
VIM for (PHP) Programmers
 
4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 

Ähnlich wie Steady with ruby

ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 

Ähnlich wie Steady with ruby (20)

Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Dsl
DslDsl
Dsl
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Ruby
 
Functional techniques in Ruby
Functional techniques in RubyFunctional techniques in Ruby
Functional techniques in Ruby
 
Otimizando Aplicações em Rails
Otimizando Aplicações em RailsOtimizando Aplicações em Rails
Otimizando Aplicações em Rails
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Elixir formatter Internals
Elixir formatter InternalsElixir formatter Internals
Elixir formatter Internals
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Steady with ruby