From: Randy Coulman Date: 2012-02-04T08:32:36+09:00 Subject: Re: Difficulty writing a sorting method (Chris Pine's Learn to Program) --001636c92a8839929b04b817ba1f Content-Type: text/plain; charset=ISO-8859-1 I'm fairly new to Ruby myself, but not to programming in general. The error message you're getting is about this line: words[0] = w just before the "def". You're trying to replace the 0th element of the words array with the value of the variable "w", but you haven't used "w" yet in your program, so it is undefined. You'll run into some additional problems when you get into your alpha_sort_words method, but feel free to ask further about those when you get there. A couple of things to think about, though: 1. What does w represent? Is it a word, or the index of a word in the words array? Sometimes you compare it with a number, and sometimes with words.all? or unsorted.all?. Think about what it really represents and try to use it consistently. 2. Array#all? is intended to take a block. I'm not sure if you've learned about those yet, as I'm unfamiliar with the book you're using. From the way you're using all? I'm not quite sure what you want the code to do, but if you get stuck later, please ask. Hope this helps, Randy On Fri, Feb 3, 2012 at 2:56 PM, claire pengelly wrote: > Hi all, I'm very, very new to programming and have been working through > Chris Pine's book. The assignment I'm working on is to write a sorting > method without just using .sort or recursion. It should sort a list of > words alphabetically. Here is what I have so far: > > #get list of words > puts "Hello, type as many words as you want, with one word per line!" > > words = [] > already_sorted = [] > unsorted = [] > while true > word = gets.chomp.capitalize > if word == '' > break > end > end > > words.push word > > #defining the sorting method > words[0] = w > def alpha_sort words > while w < 1 > if w < words.all? > already_sorted << w > end > end > while w < words.length > if w < unsorted.all? > already_sorted << w > end > w += 1 > end > end > puts(alpha_sort(words)) > > The problem seems to be in using a variable to represent the array from > the earlier list as part of defining the alpha_sort method? I don't know > why that would be a problem though. And I'm sure there's probably a > bunch of other stuff wrong with it that I can't even see! > Getting the word list works fine, but afterwards this is the error I get > when running it: > "newwordlist.rb:14:in 'main': undefined local variable or method 'w' for > main:Object (name error)" > > Thanks for your suggestions! > > -- > Posted via http://www.ruby-forum.com/. > > -- Randy Coulman rcoulman@gmail.com Twitter: @randycoulman --001636c92a8839929b04b817ba1f--