Steve Jenson's blog

Higher Order Select in Ruby

Higher Order Select in Ruby

Higher Order Select in Ruby

When I was converting my blog to jekyll, I had to write a nested select in Ruby and found it to be a little painful.

In Ruby:

# For a given feed, return all the entries that
# are blog posts rather than templates, etc.
def posts(feed)
  # The post must have a category of type #post do |entry|
    ! do |c|
      c.term == ''

In Scala, things are a little simpler thanks to anaphora: the ability to easily reference earlier state implicitly. That’s what the _ means in this context.

feed.entries.filter(!_.categories.filter(_.term == "").isEmpty)

Imagine the following sentence in English: “Steve used Steve’s keys to start Steve’s car”. Most programming languages insist on that level of verbosity.

Raganwald has a nice piece exploring Anaphora in Ruby.

# San Francisco — 13 December, 2009