Extending Existing Classes Whenever You Want

Minor Correction: The original name of this post was Extending Classes at Runtime. For Ruby, that title is okay. For ObjC , that title is wrong(AFAIK).

This is an powerful feature which two languages I know implement: Ruby and ObjC. In ObjC, you define a category and all the methods in the category will be added to the class at runtime. Therefore, even if you are using closed-source libraries, if you wanted to add a method/correct a method for the existing class, you can create a category and do so. In Ruby, it is even easier to extend classes at runtime:

Here’s a Ruby example(usual GPL disclaimers apply, you can also get the code in the file labeled extending_classes.rb from the Box widget on the right):
#!/usr/bin/env ruby
class Array

def sum
total = 0
self.each {|elem| total += elem.to_i if elem.methods.include?(to_i)}
total
end

# doesn’t do what is
# intended if elements don’t support a proper to_s
def split
self.collect! {|el| el.to_s.split(/\B/) if el.methods.include?(to_s) }
end

end

if __FILE__ == $0
a = Array.new([1,2,3,4,5,6])
b = Array.new
b << 3 << [1,2] << Foobah
c = Array.new([a,b,c,d,1])
puts a.sum is #{a.sum}
puts b.sum is #{b.sum}
puts c.sum is #{c.sum}
puts a.split is #{a.split}
puts b.split is #{b.split}
puts C’s contents:
c.each {|elem| puts elem}

end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s