Not sure this isn't working.
>> params[:payments]
{"0"=>{":amount_paid"=>"80.00", ":date_paid"=>"2/27/2008"}, "1"=>{":amount_paid"=>"100.00开发者_StackOverflow中文版", ":date_paid"=>"5/8/2008"}}
So I can call a specific object with this :
>> params[:payments][:"1"]
{":amount_paid"=>"100.00", ":date_paid"=>"5/8/2008"}
But if I write this..
>> params[:payments].each_with_index{|item, idx| item[:"#{idx}"]}
TypeError Exception: Symbol as array index
Idealistically, I want to accomplish this :
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
Update:
Based on some answers, I'ved tried this :
params[:payments].each{|k,v| @calc.payments[k.to_i] = v[":amounts_paid"]}
This turns @calc.payments
into :
nil
nil
Backing up though, the others seem to work..
>> params[:payments].each{|k,v| p v[":amount_paid"]}
"80.00"
"100.00"
And this one..
>> params[:payments].each{|k,v| p @calc.payments[k.to_i]}
{:date_awarded=>"1/2/2008", :judgement_balance=>1955.96}
nil
How can I access item[idx]
in a loop?
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
Update:
Ok, ok, here is a complete program .. script .. that you can actually run. Since you are trying to make sense of Ruby I think you should work with it outside of Rails for a few minutes. I mocked up @calc.payments
, whatever that is. This code will run and apparently do what you want.
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
If you run it you should see:
{: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}]
You could just do a this to access the values. Since params[:payments]
contains a hash, then for each pass through, key
, will be assigned the "0", "1", etc., and value
will be assigned the hash with amount_paid
and date_paid
.
params[:payments].each do |key, value|
amount_paid = value[":amount_paid"]
...
end
精彩评论