On Feb 3, 2008 1:09 AM, Tim <TimWelsh5 / gmail.com> wrote:
> I'm new to ruby and I have the following code:
>

Add
   smallest = nil
   smallest_index = 0
here, and your code will work.


>   index=0
>   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) ?

The variable is not "pass"-based - it is "scope" based, ie, it only
exists inside a particular *lexical* - that is, textual - part of your
program (in this case, your if statement, NOT the loop).  In other
words, you get a new variable for each pass through the loop.

By adding the initialization, you get th same variable all loop iterations.

Here is another variant of your code that uses essensially the same
algorithm and simplifies the code a bit:

 smallest_index = 0
 smallest_value = nil
 unsorted_array.each_with_index do |value, index|
    if !smallest_value || value<smallest
       smallest=value
       smallest_index=index
    end
 end


Eivind.