17. 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)
18. 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}"
23. 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
25. class Account
# ...
private
def schedule_billing
# ...
end
end
!
class BillingRunner
def initialize(account)
@account
end
!
def run!
# ...
@account.send(:schedule_billing)
# ...
end
end
26. class Account
# ...
private
def schedule_billing
# ...
end
end
!
class BillingRunner
def initialize(account)
@account
end
!
def run!
# ...
@account.send(:schedule_billing)
# ...
end
end
28. class User
def admin!
@role = :admin
end
!
def admin?
@role == :admin
end
!
def client!
@role = :client
end
!
def client?
@role == :client
end
end
29. 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
32. 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}
33. 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}
34. 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
39. 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"
40. Person = Class.new()
p = Person.new
!
!
p.sense
# NoMethodError: undefined method `sense' …
!
!
p.extend TehForce
p.sense
# => "... a disturbance in the force"
50. 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