class Player
def initialize(hp, attack, defence, gold)
@hp = hp
@attack = attack
@defence = defence
@gold = gold
@inventory = inventory
end
def inventory
@inventory = []
end
def buy(item)
if @gold >= item.price
@gold-=item.price
puts "You hand over #{item.price} gold, and get the #{item.name}."
puts "You have #{gold} gold left over."
@inventory.push([item.name,item.price,item.attack,item.defence])
puts "ITEMS IN INV: #{@inventory}" # output: ITEMS IN INV: [["Dagger", 4, 1, 0], ["Mucky Tunic", 2, 0, 2]]
else
puts "You can't afford this item."
end
end
end
player = Player.new(10,1,2,6)
puts player.inventory.inspect # output: []
inventory.push
行在元素位于方法内时将元素推送到数组,但是当在方法外部返回时,inventory
数组为空。这是令人困惑的,因为在该方法内以相同方式更改的其他变量将返回为更改。
从buy方法内部打印时的样本输出:
ITEMS IN INV: [["Dagger", 4, 1, 0], ["Mucky Tunic", 2, 0, 2]]
在方法之外使用player.inventory.inspect
输出:
[]
答案 0 :(得分:3)
每当您拨打<textarea id="outputField" placeholder="output" readonly autocomplete="off"></textarea>
方法时:
inventory
...它为def inventory
@inventory = []
end
分配一个新的(空)数组,从而覆盖任何现有项目。
正确的方法是在@inventory
中分配@inventory
,然后从getter中返回它:
initialize
或根本不在class Player
def initialize(hp, attack, defence, gold)
@hp = hp
@attack = attack
@defence = defence
@gold = gold
@inventory = []
end
def inventory
@inventory
end
# ...
end
中分配它并使用conditional assignment运算符:
initialize
只有在class Player
def initialize(hp, attack, defence, gold)
@hp = hp
@attack = attack
@defence = defence
@gold = gold
end
def inventory
@inventory ||= []
end
# ...
end
或[]
时(即您第一次调用@inventory
时)才会将nil
分配给false
。
也可以通过attr_reader
创建一个只返回相应实例变量的getter(如前例所示):
inventory
答案 1 :(得分:0)
我发布了这个帖子10秒后,在弄乱了一个小时之后就知道了。
我需要将inventory
添加到def initialize
,然后将空数组传递给player = Player.new(10,1,2,6)
,使其变为player = Player.new(10,1,2,6,[])
。
我仍然不知道为什么会这样。