Introduction
I had the idea to call an object method through a collection, this is how i did..
Make a simple Object class person with money method
class Person
attr_accessor :money
end
You can pass by a Proc like that
You grab new instance of John et Bob
john, bob = Person.new, Person.new
Defined Proc set_money
set_money = Proc.new do |person, money|
person.__send__ :money=, money
end
And you can iterate on your object collection and call your proc, like that
[john, bob].map do |person|
set_money.call person, rand(100)
end
puts "John have #{john.money}$"
puts "Bob have #{bob.money}$"
You obtain that
=> John have 44$
=> Bob have 74$
Ok great its cool, but i want go more deeper…
You can Monkey Patch Array with method missing like that
class Array
def method_missing method_name, *args
self.each do |element|
raise "undefined method `#{method_name}` for #{element}" unless element.respond_to?(method_name)
element.public_send(method_name, *args) if element
end
end
end
You start again
begin
john, bob = Person.new, Person.new
[john, bob].__send__ :money=, 100
puts "John have #{john.money}$"
puts "Bob have #{bob.money}$"
end
You obtain that
=> John have 100$
=> Bob have 100$
Yeah! It work! Seems look better, no? Ok ok.. NO! It’s not a good idea to Monkey Patch Array, but you can make that on different way, look that:
I’m defined a wrapper class, for encapsulate my modified Array Class
class Wrapper < Array
def self.wrap object
if object.kind_of? Array
array = new
object.each do |element|
raise 'none recursive array are supported' if element.kind_of? Array
array << element
end
array
else
object
end
end
def method_missing method_name, *args
self.each do |element|
element.__send__(method_name, *args) if element && element.respond_to?(method_name)
end
end
end
Start again
begin
john, bob = Person.new, Person.new
Wrapper.wrap([john, bob]).__send__ :money=, 100
puts "John have #{john.money}$"
puts "Bob have #{bob.money}$"
end
You obtain that
=> John have 100$
=> Bob have 100$
Ok it the really good way for that, you can serve to behavior of chosen class without altering for all of your application scope.








