Hello,

The use of "for loops" isn't very common in Ruby. It's preferable to use
iterators like "each".

And you don't need to count how many elements are in the array, you can
simply use a.size to get it (just be sure to verify it's greater than 0
before calculating the mean).

Another thing: the "return" keyword isn't very used in Ruby because the
last expression's value is automatically returned from each function. See
below.

You could rewrite your solution as:

def mean(a)
  sum =3D 0
  a.each do |x|
    sum +=3D x
  end

  if a.size > 0
    sum / a.size
  else
    0
  end

There's also a solution using reduce() in one line, but it's too early for
this.

-----
Carlos Agarie
Software Engineer @ Geekie (geekie.com.br)
+55 11 97320-3878
@carlos_agarie


2013/12/17 Johanna Bettina <lists / ruby-forum.com>

> Hello,
> I=B4m a girl form Germany and I need your help.
> I have to do a task for university and I=B4m trying for hours, but it
> never works :/. Maybe you can help me. I would be so happy!
>
> The task is to make a function called "mean(a)", for this function we
> take a array we can build by ourselves, for example a =3D [1,4,5,7]. So
> this function should summ up the elements of the array (for example 1 +
> 4 + 5 + 7] and then divide this sum with the count of the members (in
> this example 4) --> sum/count --> also called mean. The function should
> return the mean. So far i got it. But then we also should be prepared
> for the case that there are no elements in the array then the function
> should return "0". But that=B4s what I don=B4t understand. We must do it =
all
> with a loop. And I don=B4t understand this. The result should also be a
> floating-point number.
>
> This is what I got so far:
>
>  a =3D [1,2,3,4,]
>
>
> def mean(a)
> count =3D 0
> summe =3D 0
>
> for x in a
>    count +=3D 1
>    summe +=3D x
> end
>
> mean=3D(summe/count)
>
> return mean
>
> end
>
> puts "#{mean(a)}"
>
>
> Would be so nice to help me.
>
> Thank you :)
>
> --
> Posted via http://www.ruby-forum.com/.