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

Convert Hash Conditions To Array Conditions (required By Find_by_tsearch)

DZone's Guide to

Convert Hash Conditions To Array Conditions (required By Find_by_tsearch)

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


class Hash
  def to_array_conditions
    [self.keys.map{|k| "#{k} = ?" }.join(" AND "), self.values].flatten
  end
end

test "convert hash conditions to array conditions" do
  assert_equal ['city = ? AND country_code = ? AND state = ?',
    "Adendorf", "DE", "Niedersachsen"], {
      :country_code => "DE",
      :state => "Niedersachsen",
      :city => "Adendorf"
    }.to_array_conditions
end
Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}