新手问题 新人求助:ArgumentError

yumaoK. · 2019年01月06日 · 最后由 yumaoK. 回复于 2019年01月06日 · 1586 次阅读

自学 ruby 用的 ruby 从入门到精通这本书籍,按照书上代码敲了一下,结果 error 了。。。 报错信息如下: Traceback (most recent call last):
2: from ./game.rb:76:in <main>' 1: from ./game.rb:34:ingo'
./game.rb:29:in `find_room_in_direction': wrong number of arguments (given 1, expected 0) (ArgumentError)

代码如下:

#实验:地下城文本冒险游戏

class Dungeon
  attr_accessor :player

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

  def add_room(reference, name, description, connections)
    @rooms << Room.new(reference, name, description, connections)
  end

  def start(location)
    @player.location = location
    show_current_description
  end

  def show_current_description
    puts find_room_in_dungeon(@player.location).full_description
  end

  def find_room_in_dungeon(reference)
    @rooms.detect { |room|room.reference == reference }
  end

  def find_room_in_direction(direction)
    find_room_in_dungeon(@player.location).connections [direction]
  end

  def go(direction)
    puts "You go " + direction.to_s
    @player.location = find_room_in_direction(direction)
    show_current_description
  end

  class Player
    attr_accessor :name, :location

    def initialize(name)
      @name = name
    end
  end

  class Room
    attr_accessor :reference, :name, :description, :connections

    def initialize(reference, name, description, connections)
      @reference = reference
      @name = name
      @description = description
      @connections = connections
    end

    def full_description
      @name + "\n\nYou are in " + @description
    end
  end

  #Player = Struct.new(:name, :location)  #可以用Struct创建用于保存数据的特殊类
  #Room = Struct.new(:reference, :name, :description, :connections)
end

#Create the main dungeon object
my_dungeon = Dungeon.new("Fred Bloggs")

#Add rooms to the dungeon
my_dungeon.add_room(:largecave, "Large Cave", "a large cavernous cave", { :west => :smallcave })
my_dungeon.add_room(:smallcave, "Small Cave", "a small claustrophobic cave", { :east => :largecave })

#Start the dungeon by placing the player in the large cave
my_dungeon.start(:largecave)

#go to another room
my_dungeon.go(:west)
my_dungeon.go(:east)

阅读报错信息显示应该是 find_room_in_direction 方法里参数个数错误,可是这个方法确实只要一个参数啊,为什么会报错呢? 希望大家能帮我解决这个问题,谢谢!

是方法内部发生了异常,

find_room_in_dungeon(@player.location).connections [direction]

这里 [] 前面多了个空格,导致当成参数了

pinewong 回复

哦,好像是的。
但是访问哈希表的值时空格也会被当成参数吗?
为什么啊?

写全了就是

find_room_in_dungeon(@player.location).connections([direction])

这应该不是你的本意了吧

pinewong 回复

emm,我以为这个方法中的空格会直接忽略掉呢,看样子是我理解错了😅
谢谢你

需要 登录 后方可回复, 如果你还没有账号请 注册新账号