From: Stefano Crocco Date: 2007-08-29T22:54:46+09:00 Subject: Re: array.sort Alle mercoled狸 29 agosto 2007, Mark Ransom ha scritto: > Hi, > > I'm a novice programmer who is just starting out in Ruby. I've been > playing around with arrays and have run into a problem: > > This works: > > array = [3,2,1] > puts array.sort > > =>123 > > BUT this doesn't (error attached): > > nums = Array.new > > numplays = 5 > > numplays.times do > > for values in 1..5 > ball = rand(56) > redo if ball == 0 || nums.include?(ball) > nums [values] = ball > end > puts nums.sort > end > > Can anyone shed light on this newby? > > Attachments: > http://www.ruby-forum.com/attachment/183/array_sort.JPG Your array ends up having 6 elements, the first of which is nil. This happens because your values variable starts from 1, while arrays indexes start at 0. sort doesn't work on arrays which contain nil elements, because nil doesn't have the <=> operator, which is used by sort to compare elements. To solve your problems, you should replace 1..5 with 0..4 (or use 5.times which, in my opinion, is much clearer). By the way, you can avoid to check whether ball is 0 by replacing ball = rand(56) with ball = rand(55) + 1 I hope this helps Stefano