hash_to_conditions

Update: This functionality is now included with Rails 1.2; just do :conditions = { :foo => bar }.

hash_to_conditions is was useful to programmatically generate the :conditions parameter for ActiveRecord::Base#find.

def hash_to_conditions(hash)
  if hash.empty?
    return nil
  else
    keys, values = hash.to_a.transpose
    sql = keys.map { |x| "#{x} = ?" }.join(" AND ")
    return [ sql, *values ]
  end
end

Demo

hash_to_conditions(:foo => 1, :bar => 2)
# => [ "foo = ? AND bar = ?", 1, 2 ]

hash.to_a.transpose?

Even though Hash#keys and Hash#values always seem to return data in matching order (in Matz’ Ruby implementation) it doesn’t seem to be guaranteed to behave that way. Thanks to LoganCapaldo at #ruby-lang for the hash.to_a.transpose solution.