github
Advanced Search
  • Home
  • Pricing and Signup
  • Explore GitHub
  • Blog
  • Login

raganwald / homoiconic

  • Admin
  • Watch Unwatch
  • Fork
  • Your Fork
  • Pull Request
  • Download Source
    • 262
    • 6
  • Source
  • Commits
  • Network (6)
  • Issues (0)
  • Downloads (1)
  • Wiki (1)
  • Graphs
  • Branch: master

click here to add a description

click here to add a homepage

  • Branches (1)
    • master ✓
  • Tags (1)
    • second.tag
Sending Request…
Click here to lend your support to: homoiconic and make a donation at www.pledgie.com ! Edit Pledgie Setup

Pledgie Donations

Once activated, we'll place the following badge in your repository's detail box:
Pledgie_example
This service is courtesy of Pledgie.

An experiment in publishing code and words about code on a small scale. — Read more

  cancel

http://github.com/raganwald/homoiconic/tree/master/homoiconic.markdown

  cancel
  • Private
  • Read-Only
  • HTTP Read-Only

This URL has Read+Write access

fixes 
raganwald (author)
Thu Feb 04 08:40:01 -0800 2010
commit  66f04606662a9df6629dabc1b9264f5e0913e58e
tree    9772eaff24fa3deaaa1c48844983ce5b0074c148
parent  bddb7277cad41914e70382d624b6ab3a9d0b02c8
homoiconic / 2008-10-27 / unfold.markdown 2008-10-27/unfold.markdown
100644 30 lines (16 sloc) 1.886 kb
edit raw blame history

unfold

Here's a little something from my old blog that I found myself using again. If you want the background, you might like my old posts Really simple anamorphisms in Ruby and Really useful anamorphisms in Ruby.

This week-end, I found myself thinking about #unfold in a new way: it's a way of turning an iteration into a collection. So anywhere you might use for or while or until, you can use #unfold to create an ordered collection instead. This allows you to use all of your existing collection methods like #select, #reject, #map, and of course #inject instead of writing out literal code to accomplish the same thing.

For example, given a class, here are all of the classes and superclasses that implement the class method #foo:

class Foo

  def self.foo_handlers
    self.unfold(&:superclass).select { |klass| klass.respond_to?(:foo) }
  end

end

The little idea here is that you don't have to write a loop of some sort climbing the class tree and accumulating an array of classes that respond to #foo as you go. This expresses the same idea in terms of operations on a collection.

Git it

The code for unfold is at unfold.rb. To use it in a Rails project, drop unfold.rb in config/initializers.


Subscribe to new posts and daily links:

Reg Braithwaite: CV, Twitter

Blog | Support | Training | Contact | API | Status | Twitter | Help | Security
© 2010 GitHub Inc. All rights reserved. | Terms of Service | Privacy Policy
Powered by the Dedicated Servers and
Cloud Computing of Rackspace Hosting®
Dedicated Server