From: Stu Date: 2011-05-08T15:16:21+09:00 Subject: Re: Lets play a guessing game. (how to code this better?) On Sun, May 8, 2011 at 12:08 AM, Super Goat wrote: > > I was thinking of asking if the player would like to play again and then > figuring out how to restart the whole thing but I wasn't sure how to do > this. How can I make prompt to "Play again?" and when answered "Yes" > restart, whether the person wins or loses (or if "No" just exits)?  Or > is the way my code is written make this impossible? > > Attachments: > http://www.ruby-forum.com/attachment/6181/meth_100guess.rb > > > -- > Posted via http://www.ruby-forum.com/. > > You can do it with more methods. In fact you should break as much down as possible. The concept is to keep every method as small as possible. Does one thing and does it well. Ruby allows you to add ? at the end of a method name which should return true/false so you could almost have it kind of tell a story. Ruby is also liberal with it's parens and has implied return statements. so for a contrived example a traditional language would look like this: def add_num( first_num, second_num) answer = (first_num + second_num) return( answer) end x = add_num( 42, 100) where in ruby it could look like this: def add_num first_num, second_num first_num + second_num end x = add_num 42, 100 methods always return a value (this is contrast to functions which do one thing and do it well but may only return success or error) Ruby has only methods. Methods give the user the ability to reuse code using the example above: x = add_num 42, 100 y = add_num( x, 16) z = add_num( y, x) puts z => 300 using good names for your methods make it easier for others to read them as well as making them easier to read years later if you ever have to revisit. Method definitions start with the def keyword, the method name, then there are optional arguments which are variables passed as copies into the scope of the method. The method body can contain the same code logic you have which reads much like a fall through shell script right now. Every method closes with the end keyword. The last statement returns regardless in ruby. My personal preference in style is to keep the parens in the definition but only use the return when I need to force it: def add_num( first_num, second_num) first_num + second_num end Once you have normalized the script in pure methods we can then begin to talk about how user created methods can relate to user created classes and start talking about object oriented programming. ~Stu