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.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}