Adam O'Connor
Adam O'Connor

Reputation: 2652

Best way to extract values from strings (regexp?)

I'm working with an app (Ruby 1.9.2, Rails 3) and an API and need interface an API given certain param values.

What's the best way to break this:

bedrooms: 3 - 7
bathrooms: 1 - 8
sqft: 1000 - 8000
price: $100000 - $800000

Into this:

bedrooms_min = 3
bedrooms_max = 7
bathrooms_min = 1
bathrooms_max = 8
sqft_min = 1000
sqft_max = 8000
price_min = 100000
price_max = 800000

Upvotes: 0

Views: 533

Answers (1)

Pavel Pravosud
Pavel Pravosud

Reputation: 629

price_input = "$100000 - $800000"
price_min, price_max = price_input.gsub(/[^\d-]/, '').split('-', 2).map(&:to_i)
price_min # 100000
price_max # 800000

So, basically we remove everything except digits and '-' sign that separates two values and then split string in two by this separator.

Upvotes: 1

Related Questions