比较哈希值

时间:2014-06-16 15:46:14

标签: ruby-on-rails ruby hash

在我的Ruby on Rails应用程序中,我有以下参数:

{"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"}} 

现在我想检查一下:

  • 1 [:from_days]> 0:TO_DAYS]
  • 2 [:from_days]> 1:TO_DAYS]

问题是我想动态地这样做,因为将来这个参数会增长。有没有人知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

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

此代码表示您的params哈希:

  • 必须包含连续的密钥(每个密钥之间没有间隙)
  • 必须包含具有[:from_days][:to_days]
  • 的哈希值