On Wednesday 11 June 2008, Jason Lillywhite wrote: > I have this simple program that has a problem that I just can't find a > solution to: > *********** > class MyArray > > def count > a = [50.1,52.0,55.0,60.0] > b = [0.24,0.1,0.29,0.9] > i = 0 > c = [] > while i <= 4 do > puts c = b.collect {|x| x * a[i]} > i += 1 > end > > end > end > > number = MyArray.new > number.count > ********* > I want each element of array 'b' to be multiplied by each element of 'a' > and return a vector, 'c' with 16 rows. > > this code works, but I get an error that says: > ArrayInsert.rb:9:in `*': nil can't be coerced into Float (TypeError) > from ArrayInsert.rb:9:in `count' > from ArrayInsert.rb:9:in `collect' > from ArrayInsert.rb:9:in `count' > from ArrayInsert.rb:17 > > I don't understand where 'nil' is coming from. Can someone help me with > this one? Thank you. Array indexes go from 0 to the number of elements of the array minus one. In your code, you allow i to be 4 (because you put <= in the while condition), then use i to access the elements of the array a. Since a has four elements, the last non-nil element has index 3. When i is 4, a[i] will return nil, giving the error you see. I hope this helps Stefano