Topic: Help with .each

Hi, I am using Higcharts to make some graphs on a rails app.
Highcharts data series are passed via array and I have a method on a model that returns a float.
I needed something like this:

Model.all.method_that_returns_float

It didnt worked besause the .all returns me an array, so i did:

Model.all.each{|model|model.method} 

But it returned just an array of the objects and not the value of the method's calculation.

Re: Help with .each

You'd have to do something like

Model.all.each do |model|
  @x = model.method
  #do something with @x
end

Or, say if you wanted to add the values of all the calculations,  you could try

@total = Model.all.each.inject{ |sum, m| sum + m.method}

if you want an array of the calculation results:

@allresults = Model.all.map {|m|, m.method }

Last edited by BradHodges (2011-11-01 16:39:29)

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Help with .each

Thanks BradHodges, second time you are helping me.
My code is this (once again, excuse the strange portuguese names of the stuff)

  def calc_imc_todos
    self.paciente.avaliacaos.each do |avaliacao|
      @part = []
      @part << avaliacao.antropometrica.imc  
    end
    return @part
  end

When I try this on the rails console the return is an array, but only with the value of the last "imc" I'm calculating at the "antropometrica" model

ruby-1.9.2-p290 :004 > antropometrica.calc_imc_todos
 => [15.615704937537183] 

Re: Help with .each

 def calc_imc_todos
    @part = []
    self.paciente.avaliacaos.each do |avaliacao|
      @part << avaliacao.antropometrica.imc  
    end
    return @part
  end

But a MUCH shorter way would be

 def calc_imc_todos
    return self.paciente.avaliacaos.map{ |avaliacao|, avaliacao.antropometrica.imc  }
  end
Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Help with .each

I'm stupid, the @part = [] was inside the each block.
Brad, thanks man, if I ever go to the U.S. I'll buy you a beer haha

Last edited by CassioGodinho (2011-11-01 17:14:55)