From: Stu Date: 2011-05-09T14:29:22+09:00 Subject: Re: Lets play a guessing game. (how to code this better?) Hi Goat, The basic skeletal structure of a ruby method is so: def method_name( arg1, arg2, *args) # and so on #.. method body return #.. or implicit return( i.e. the keyword is optional) end In traditional languages you have a return keyword which returns a value to the caller. In ruby everything is a caller and everything is a sender. This is another paradigm you'll come to understand the more you work with ruby. very contrived example: def return_42( ) return( 42) end is equivalent to def return_42 42 end Here is another conceptual example with my style please try it in irb. I will create a adder method and then create a square method using the the previous methods in effort to show you how methods can be reused: def adder( x,y) x + y end def square_num( x) y = 0 count = 0 while count != x y+=adder( x,0) count += 1 end return( y) end irb session: >> square_num( 3) => 9 >> adder( 1, 4) => 5 >> square_num( adder( 3, 1)) => 16 >> adder( square_num( 3), square_num( 5)) => 34 starting with the adder method I did not use a return statement. I could have rewritten the last line as return( x+y) but I didn't. It's up to you to figure out if it's more readable with or without it. Either way if I write this code: var = adder( 41, 100) # the variable 'var' will be populated with the return value from the function adder. The square_num( ) method reuses the adder method in a conditional while loop. Though contrived for this example it's a good way to understand methods to be composed for reuse. When you get to get to OOPS programming there is a concept of composite objects. The concept is the same but in a less linear fashion. You'll also notice I used the return statement in the square_num( ) method. I did this because I personally feel the freestanding variable 'y' looks awkward and less readable. Others opinion on the subject may vary. It's up to you to decide what works best and use those conventions. A more succinct way to write the square_num( ) method would be this: def square_ruby_way( x) y = 0 x.times { y+=adder(x,0) } y end The right ruby way( and quickest) with the most most brevity would be to use ruby's built in power of operator method: def best_ruby_square( x) x**2 end The first example of course removes the while loop and follows one of ruby's object oriented conventions. I don't want to get to deep into it as it is a abstraction of a while loop and begins to expose some of ruby's built in iterator design patterns. The times method should be saved for another discussion after you get your bearings with method creation and definition. ~Stu