public
Created

Using &block as constructor

  • Download Gist
block_constructor.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# &block constructors
# From http://www.deploymentzone.com/2011/06/23/block-constructors
 
# If you need a behavior like this in your class:
Person.new do |p|
p.first_name = "John"
p.last_name = "Brown"
p.dob = Date.parse("5/9/1800")
end
 
# You can achieve it with this snippet:
class Person
attr_accessor :first_name, :last_name, :dob
 
def initialize
yield self if block_given?
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.