Hi --
On Sun, 9 Jul 2006, Dark Ambient wrote:
> On 7/9/06, dblack / wobblini.net <dblack / wobblini.net> wrote:
>
>>
>> There's no issue of nil being smaller or larger than anything. The
>> first time through your loop, lowest is nil -- which means that the
>> item < lowest comparison is never evaluated.
>
>
> Okay, I sort of see that.
>
> The next time through,
>> lowest is "five", so item < lowest is evaluated. It's false, so the
>> next statement (lowest = item) is not executed.
>
>
> Don't get this looking at the 'if' statement
>
> if lowest == nil || item < lowest
> lowest = item
>
> First confusion is || , this I take to be 'or' ?
> Second, if the assignment of 'lowest = item' comes after the 'if'
> conditional, how does any 'tem become the lowest. The way I'm reading the
> statement (using the array - mylist = ['five', 'eight', 'one', 'ten',
> 'nine']) I interpret the second iteration as
> if lowest == nil or 'five' < lowest # lowest is still equal to nil ?
> Or could it be that in the 'if' block, the 'lowest = item' is set before the
> 'if conditons' are checked ?
No, definitely not. It's all very linear:
if <some expression is true>
do this
end
If the expression isn't true, then "do this" never gets executed.
You might put some extra output in your loop, so you can see what's
going on:
def sort(list)
sorted = []
unsorted = []
lowest = nil
list.each do |item|
puts "Comparing #{item.inspect} (item) to #{lowest.inspect} (lowest)"
if lowest == nil || item < lowest
puts "Either lowest is nil, or #{item.inspect} is less than #{lowest.inspect}"
puts "So lowest is now being set to #{item.inspect}"
lowest = item
end
end
puts "Loop finished: lowest is #{lowest.inspect}"
sorted.push(lowest)
puts sorted
end
mylist = ['five', 'three', 'one', 'ten', 'eight']
sort mylist
The output is:
Comparing "five" (item) to nil (lowest)
Either lowest is nil, or "five" is less than nil
So lowest is now being set to "five"
Comparing "three" (item) to "five" (lowest)
Comparing "one" (item) to "five" (lowest)
Comparing "ten" (item) to "five" (lowest)
Comparing "eight" (item) to "five" (lowest)
Either lowest is nil, or "eight" is less than "five"
So lowest is now being set to "eight"
Loop finished: lowest is "eight"
David
--
http://www.rubypowerandlight.com => Ruby/Rails training & consultancy
http://www.manning.com/black => RUBY FOR RAILS, the Ruby book for
Rails developers
http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log
dblack / wobblini.net => me