rails/rails — pull request #5706 by amiel (2012-04-02 21:39:22+00:00)
Title: Use symbols in case statements for great justice

This is syntactic sugar for case statements.

```ruby

case user
when ~:admin?
# Do stuff
when ~:active?
# Do stuff
end
```

Would be equivalent to:

```ruby
if user.admin?
# Do stuff
elsif user.active?
# Do stuff
end

```

With the added benefit that if `user` is a method, it would only get called once.

## Rationale

The short answer is because it looks nice.

ActiveSupport does a great job of extending ruby with simple conveniences like `Symbol#to_proc` which has now been merged in to ruby core. I think this could be part of the sugar that makes Ruby sweeter.

## Unary method

I chose the unary method `~` because I don't see it having any other use for `Symbol`, but it could just as easily be `+` or `-`.

## Negation

In offering this support I also thought about supporting negation: https://github.com/amiel/rails/compare/rails:master...case_with_predicates_and_negative

## Implementation discussion

I tried a few different implementation concepts for this. This one is by far the simplest.

In ruby 1.9, procs respond to `===` for use in case (see http://www.aimred.com/news/developers/2008/08/14/unlocking_the_power_of_case_equality_proc/)

Here are a couple of other options:

1. My first concept was to override `Symbol#===`, which offered the nicest syntax, but I felt was too obtrusive.
2. In another version, `Symbol#~` returns an object that responds to `===`, this is also concise, but not as simple as the other two options. However, it offers the most complete support for negation. Here's an example implementation that also supports negation: https://github.com/amiel/rails/compare/rails:master...case_with_predicates_with_object