On Feb 2, 2008 6:09 PM, Tim <TimWelsh5 / gmail.com> wrote:
> I'm new to ruby and I have the following code:
>
>   index=0

you could insert "smallest = nil" here

>   unsorted_array.each do |value|
>     if index==0
>       smallest=value
>       smallest_index=0
>     elsif value<smallest
>       smallest=value
>       smallest_index=index
>     end
>     index=index+1
>   end
>
> When it gets to index 1, it crashes and says that smallest is
> undefined (on the elsif line).  Why is that, when it gets defined in
> the first pass (index = 0) ?

Not sure what you are trying to do, but if your data is not unique...

a = 5,1,4,7,2,1,9,2,1
smallest = a.min
s_indexes = []
a.each_with_index {|v, i| s_indexes << i if v == a.min}

If you don't want to do it that way, then...

a = 5,1,4,7,2,1,9,2,1
smallest, s_indexes = a.first, []
a.inject(a.first) {|m, e| e < m ? e : m}
a.each_with_index {|v, i| s_indexes << i if v == a.min}

Todd