Created
June 30, 2011 00:12
-
-
Save jonaphin/1055331 to your computer and use it in GitHub Desktop.
Class#to_proc Implementation
This file contains hidden or 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
### Jonathan Lancar - https://github.com/jonaphin ### | |
######################### | |
#### Class#to_proc #### | |
######################### | |
class Class | |
# Initialize multiple objects at once | |
def to_proc | |
proc{ |*args| self.new *args } | |
end | |
end | |
## USE CASE ## | |
class Building | |
attr_accessor :name, :height | |
def initialize args | |
args.each{ |key, val| instance_variable_set("@#{key}", val) unless val.nil? } | |
end | |
def to_s | |
"The #{name} building is #{height.to_s}ft high" | |
end | |
end | |
params = [{:name => "Empire State", :height => 1250}, {:name => "Taipei 101", :height => 1671}].map &Building | |
p params.collect &:to_s | |
# => ["The Empire State building is 1250ft high", "The Taipei 101 building is 1671ft high"] | |
=begin | |
#### Reasoning #### | |
When dealing with an array filled with multiple elements of data from a same source, we often see ourselves in need of | |
transforming each element into their corresponding data type. A Class#to_proc could try to initialize itself into an object | |
of the type it represents, using each argument it is being passed into its constructor. | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment