attr_accessor - 从另一个类访问对象属性

时间:2016-12-01 15:30:18

标签: ruby object attributes

我想从Human's类中访问食人魔的对象的swings属性。但是,我得到的只是: NameError: undefined local variable or method ogre for **<Human:0x007fdb452fb4f8 @encounters=3, @saw_ogre=true> 很可能是一个简单的解决方案,我的大脑今天早上没有运作。我正在用minitest运行测试。测试和课程如下:

ogre_test.rb

def test_it_swings_the_club_when_the_human_notices_it
  ogre = Ogre.new('Brak')
  human = Human.new
  ogre.encounter(human)
  assert_equal 0, ogre.swings
  refute human.notices_ogre?

  ogre.encounter(human)
  ogre.encounter(human)

  assert_equal 1, ogre.swings
  assert human.notices_ogre?
end

ogre.rb

class Ogre
  attr_accessor :swings
  def initialize(name, home='Swamp')
    @name = name
    @home = home
    @encounters = 0
    @swings =  0
  end

  def name
    @name
  end

  def home
    @home
  end

  def encounter(human)
    human.encounters
  end

  def encounter_counter
    @encounters
  end

  def swing_at(human)
    @swings += 1
  end

  def swings
    @swings
  end
end


class Human

  def initialize(encounters=0)
    @encounters = encounters
    @saw_ogre = false
  end

  def name
    "Jane"
  end

  def encounters
    @encounters += 1
    if @encounters % 3 == 0 and @encounters != 0
      @saw_ogre = true
    else
      @saw_ogre = false
    end
    if @saw_ogre == true
      ogre.swings += 1 # <----issue
    end
  end

  def encounter_counter
    @encounters
  end

  def notices_ogre?
   @saw_ogre
  end
end

1 个答案:

答案 0 :(得分:0)

简单的解决方法是将ogre对象作为参数传递给encounters - 假设在没有参数的情况下其他任何地方都没有使用encounters

class Ogre
  ...

  def encounter(human)
    human.encounters(self)
  end

  ...    
end


class Human
  ...

  def encounters(ogre)
    @encounters += 1
    if @encounters % 3 == 0 and @encounters != 0
      @saw_ogre = true
    else
      @saw_ogre = false
    end
    if @saw_ogre == true
      ogre.swings += 1 # <----issue
    end
  end

  ...
end