Mateusz Urbański
Mateusz Urbański

Reputation: 7862

Comparing hash values

In my Ruby on Rails application i have the following params:

{"0"=>{"from_days"=>"1", "to_days"=>"2", "netto_price"=>"1.0", "_destroy"=>"false", "id"=>"57"}, "1"=>{"from_days"=>"3", "to_days"=>"7", "netto_price"=>"23", "_destroy"=>"false"}, "2"=>{"from_days"=>"9", "to_days"=>"10", "netto_price"=>"123", "_destroy"=>"false"}} 

Now i want to check that:

Problem is that I want to do it dynamically because in future this parameters will grow up. Did anyone have idea how to solve this problem?

Upvotes: 0

Views: 51

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

You can try this:

params = {"0"=>{"from_days"=>"1", "to_days"=>"2", "netto_price"=>"1.0", "_destroy"=>"false", "id"=>"57"}, "1"=>{"from_days"=>"3", "to_days"=>"7", "netto_price"=>"23", "_destroy"=>"false"}, "2"=>{"from_days"=>"9", "to_days"=>"10", "netto_price"=>"123", "_destroy"=>"false"}}

(params.keys.min..params.keys.max).each do |index|
  if params[(index+1).to_s][:from_days].to_i > params[index.to_s][:to_days].to_i
    # your logic when 1[:from_days] > 0[:to_days] is true
  else

  end
end

This code implies that your params hash :

  • must contain consecutive keys (no gap between each)
  • must contain a hash having the [:from_days] AND the [:to_days] keys

Upvotes: 2

Related Questions