获取实例属性而不是未定义的方法

时间:2017-01-22 15:50:20

标签: crystal-lang

class Place
  @description = "Default place"

  def initialize(x : Int32, y : Int32, description : String)
    @x = x
    @y = y
    @description = description

    puts "Description of this place is: #{description}"
  end
end



require "./browser-game/*"
require "./places/*"

module Browser::Game
  # TODO Put your code here
  place = Place.new 2, 3, "Yay new description"

  puts place.description
  puts "End of the program"
end

我收到此错误:

  

browser-game.cr:8中的错误:Place

的未定义方法'description'
puts place.description
           ^~~~~~~~~~~

1 个答案:

答案 0 :(得分:0)

写下这个:

class Place
  getter :description
  @description = "Default place"

  def initialize(x : Int32, y : Int32, description : String)
    @x = x
    @y = y
    @description = description

    puts "Description of this place is: #{description}"
  end
end

getter用于从实例授予对read属性的访问权限。 setter用于设置。如果没有这个,编译器将尝试访问该方法,因为您没有访问该属性。