Take me home

Case or hash

Published September 26, 2008

A case statement:

redirect_to case request.domain
when "foo.com"
  some_path
when "bar.com"
  other_path
else
  default_path
end

Here, every case does the same thing. It gives redirect_to an argument. I think that you should use a hash instead.

DOMAIN_MAPPINGS = {
  "foo.com" => some_path, "bar.com" => other_path
}

redirect_to DOMAIN_MAPPINGS[request.domain] || default_path

As hashes and case statements are sort of similar, I prefer to make a clear distinction between them. I only use case statements when I'm doing different things on each case. Such as this:

case current_user.role?
when :admin
  send_email
when :editor
  add_to_messages
else
  restrict_access!
end

Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.