开发者

ruby class problem

I have the following ruby code:

class Mp
  def initialize

    Test.new.mytest
    Work.new.mywork
    ha
    address

  end

  def h开发者_如何学运维a
    puts "message from ha"
  end

  def address

   a='see'

  end

end


class Test

  def mytest
    m=Mp.new
    puts "Message from test do you #{m.address}"
  end
end

class Work

  def mywork
    puts "message from work"
  end

end

Mp.new

This works fine except the part in def mytest where I'm trying to put out the m.address. Thanks for your help in advance.


Actually the reason it doesn't work has nothing to do with printing the address. It's one line before that:

m = Mp.new this creates a new Mp object. However inside Mp's initialize method a new Test object is created and its mytest method is called. The mytest method then again creates a new Mp object and so on. In other words: Test#mytest and Mp#initialize are mutually and infinitely recursive.

Edit in response to your comment:

I'm not quite sure I understood the question. If you mean "How do I access the variable a which was set in the address method, after address has been called": you don't. a is a local variable that goes out of scope once the method has returned. If you want to set an instance variable use @a = 'see'. @ denotes instance variables in ruby. If you want to be able to access that variable from outside the object, use attr_accessor :a to define accessor methods for @a.

An example:

class Mp
  attr_accessor :c

  def initialize
    initialize_variables
    puts @c
    puts @b # I can access @c and @b here because it's an instance variable
            # and I'm within the same object

    # puts a # This does not work because a is a local variable from the
             # initialize_variables method and no longer in scope
  end

  def initialize_variables
    a = "a"
    @b = "b"
    @c = "c"
    puts a  # I can access a here because I'm still inside the method
            # where a was defined
  end
end

m = Mp.new
# puts m.a
# puts m.b  # These don't work because there are no methods a or b

puts m.c  # This works because attr_accessor defined a method c which
          # returns the content of m's @c variable


You've got an infinite loop. You create a new object of class Mp, which in turn creates a new object of class Test and then calls its mytest method, which in turn creates another object of class Mp, which in turn...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜