你如何在.each_with_index中调用索引

时间:2011-01-29 03:42:58

标签: ruby-on-rails loops params

不确定这不起作用。

>> params[:payments]
{"0"=>{":amount_paid"=>"80.00", ":date_paid"=>"2/27/2008"}, "1"=>{":amount_paid"=>"100.00", ":date_paid"=>"5/8/2008"}}

所以我可以用这个来调用一个特定的对象:

>> params[:payments][:"1"]
  {":amount_paid"=>"100.00", ":date_paid"=>"5/8/2008"}

但如果我写这个..

>> params[:payments].each_with_index{|item, idx| item[:"#{idx}"]}
TypeError Exception: Symbol as array index

理想情况下,我想完成这个:

params[:payments].each_with_index do |item, idx|      
  @calc.payments[idx][:date_paid] = item[:"#{idx}"][":amount_paid"]
  @calc.payments[idx][:amount_paid] = (item[:"#{idx}"][":amount_paid"]).to_f
end

更新

根据一些答案,我试过这个:

params[:payments].each{|k,v| @calc.payments[k.to_i] = v[":amounts_paid"]}

这会将@calc.payments变为:

nil
nil

支持,其他人似乎工作..

>> params[:payments].each{|k,v| p v[":amount_paid"]}
"80.00"
"100.00"

这一个..

>> params[:payments].each{|k,v| p @calc.payments[k.to_i]}
{:date_awarded=>"1/2/2008", :judgement_balance=>1955.96}
nil

如何在循环中访问item[idx]

2 个答案:

答案 0 :(得分:1)

params[:payments].each do |k,v|
  puts "Item %d amount=%s date=%s\n" % [k, v[":amount_paid"], v[":date_paid"]]
end
Item 0 amount=80.00 date=2/27/2008
Item 1 amount=100.00 date=5/8/2008

更新:

好的,好的,这是一个完整的程序..脚本..你可以实际运行。 因为你试图理解Ruby,我认为你应该在Rails之外使用它几分钟。我嘲笑@calc.payments,无论那是什么。这段代码会运行,显然可以做你想要的。

require 'pp'
(params = {})[:payments] = {"0"=>{":amount_paid"=>"80.00", ":date_paid"=>"2/27/2008"}, "1"=>{":amount_paid"=>"100.00", ":date_paid"=>"5/8/2008"}}
pp params
class T; attr_accessor :payments; end
(@calc = T.new).payments = []
params[:payments].each do |k,v|
  i = k.to_i
  @calc.payments[i] ||= {}
  @calc.payments[i][:date_paid]   = v[":date_paid"]
  @calc.payments[i][:amount_paid] = v[":date_paid"].to_f
end
pp @calc.payments

如果你运行它,你应该看到:

{:payments=>
  {"0"=>{":amount_paid"=>"80.00", ":date_paid"=>"2/27/2008"},
   "1"=>{":amount_paid"=>"100.00", ":date_paid"=>"5/8/2008"}}}
[{:date_paid=>"2/27/2008", :amount_paid=>2.0},
 {:date_paid=>"5/8/2008", :amount_paid=>5.0}]

答案 1 :(得分:0)

你可以这样做来访问这些值。由于params[:payments]包含哈希值,因此对于每次传递,key将分配“0”,“1”等,并且value将被分配哈希值{ {1}}和amount_paid

date_paid