Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Convert A Conditions Hash To A SQL LIKE Conditions Array

DZone's Guide to

Convert A Conditions Hash To A SQL LIKE Conditions Array

·
Free Resource
Inspired by http://snippets.dzone.com/posts/show/4734

USAGE
my_hash = {name => 'foo', location => 'bar'} 
my_hash.to_like_conditions # returns ["name LIKE ? and location LIKE ?", "%foo%", "%bar%"]


class Hash
  def to_like_conditions
    conditions = [self.keys.map{|k| "#{k} LIKE ?" }.join(" AND ")]
    conditions << self.values.map{|v| "%#{v}%" }
    conditions.flatten
  end
end
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}