Created
July 1, 2011 14:22
-
-
Save rgo/1058634 to your computer and use it in GitHub Desktop.
Using &block as constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# &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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment