简单的Ruby类令人困惑和调试

时间:2012-07-28 03:21:56

标签: ruby ruby-on-rails-3

我正在尝试使用下面的ruby类,我只是不明白输出语句的结果是如何调用播放器函数后跟新变量的“John Smith”?

有没有更简单的方法?编码器以一种让我困惑的方式做到了 最后,你能告诉我如何在TextMate上调试Ruby类或任何ruby代码吗?我的意思是调试就像在Visual C ++中进行调试一样,向我显示第一行被调用并被激活,然后跳转到下一行......看看它是如何工作的?

class Dungun
  attr_accessor :player 

def initialize(player_name)
  @player = Player.new(player_name)
  @rooms = []
end


class Player
  attr_accessor :name, :location
  def initialize(player_name)
    @name = player_name
  end
end

class Room
  attr_accessor :reference, :name, :description, :connection
  def initialize(reference,name,description,connection)
    @reference = reference
    @name = name
    @description = description
    @connection = connection

  end
end
end

my_dungun = Dungun.new("John Smith")
puts my_dungun.player.name

1 个答案:

答案 0 :(得分:3)

执行顺序

# 1. Called from my_dungun = Dungun.new("John Smith")
Dungun.new("John Smith")

# 2. Inside Dungun it will call the initialize from Dungun class
initialize("John Smith")

# 3. The initialize method, from Dungun class, will have this statement saying
# that instance variable @player will receive the
# result of Player.new("John Smith")
@player = Player.new("John Smith")

# 4. The Player's 'new' method will call the
# inner class Player's initialize method
initialize("John Smith")

# 5. The Player's initialize should assign "Jonh Smith" to @player's name
@name = "John Smith"

# 6. Then head back to where we stopped, and continue to the other
# statement at second line inside Dungun's 'new' method
@rooms = []

阅读Mastering the Ruby Debugger以获取ruby调试宝石和一些课程!