Skip to content

Instantly share code, notes, and snippets.

@fernandolopez
Created January 22, 2015 20:11
Show Gist options
  • Save fernandolopez/74089bc01264e6d1e778 to your computer and use it in GitHub Desktop.
Save fernandolopez/74089bc01264e6d1e778 to your computer and use it in GitHub Desktop.
List comprehensions simuladas en Ruby

Trying to emulate list comprehensions syntax I came with this syntax that resembles haskell list comprehensions (by having several guards separated by , and allowing zero guards):

> (1..24).comp { |x| [x, x.even?, x > 6] }
=> [8, 10, 12, 14, 16, 18, 20, 22, 24]

> [nil, nil, 1, 2, 3, 4, 5].comp { |x| [x, x != 4] }
=> [nil, nil, 1, 2, 3, 5]

> [nil, nil, 1, 2, 3, 4, 5].comp { |x| [x] }
=> [nil, nil, 1, 2, 3, 4, 5]

This solution may not be the fastest but doesn't destroy nil values and is similar to list comprehensions syntax.

The implementation is:

module Enumerable
  def comp(&block)
    return self if block.nil?
    self.map(&block).select do |x, *cond|
      cond.all?
    end.map { |x, *rest| x }
  end
end

The block receives each element of the Enumerable and returns an Array, where the first element is the value, and the rest are the boolean guards (if any).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment