From: "Jan E." Date: 2012-07-02T01:38:30+09:00 Subject: Re: Question on Learning Ruby the Hard Way Hi, For the next time, please *attach* the code rather than post it. The forum software inserts a line break after every 80 characters or so, which destroys the whole formatting. It also seems you've silently left out several methods. Of course you can shorten the code, but then you should tell us. Well, for this particular example we can more or less guess which methods are missing and what they look like. But if this was a more complicated class, it would really be annoying to get an error message and having to figure out what's missing. To the actual questions: Michael Sung wrote in post #1066882: > def play() > next_room = @start > > while true > puts "\n--------" > room = method(next_room) > next_room = room.call() > end > end > > > I can see that variable next_room is set to instance variable @start. > But how does this "while" loop work? I'm also not familiar with how > "method" and "call" are both used here, as well as the : used in return > (e.g. return :central_corridor) below. The while loop is an endless loop. You probably know how a while loop works in general. In this case the condition is always true, so the loop will run forever. However, it would have been better to use an explicit endless loop like Kernel#loop: loop do # body end Calling "method" with a method name as a Symbol creates a Method object for this method. This object can then be passed around and called at any time (by calling the "call" method): class A def f puts "f called" end end a = A.new f = a.method(:f) #create a Method object for method "f" p f f.call() # call Method object (without arguments) See http://ruby-doc.org/core-1.9.3/Object.html#method-i-method http://ruby-doc.org/core-1.9.3/Method.html The Game class uses this to call methods dynamically: Every method like "central_corridor" or "laser_weapon_armory" returns the name of the method which should be called next (as a Symbol). This allows the user to control the flow of the game. For example, if he's in the central corridor and types in "shoot!", the "death" method will be called. If he types in "tell a joke", the "laser_weapon_armory" method will be called (he continues to the next room). However, a better way to achieve this is by using Object#send. This method takes a method name as a Symbol together with optional arguments and then calls this method. So you can replace room = method(next_room) next_room = room.call() with next_room = send next_room See http://ruby-doc.org/core-1.9.3/Object.html#method-i-send It may also be a good idea to use "public_send" instead, which will only call public methods: http://ruby-doc.org/core-1.9.3/Object.html#method-i-public_send -- Posted via http://www.ruby-forum.com/.