【问题标题】:Get instance property instead of undefined method获取实例属性而不是未定义的方法
【发布时间】:2017-01-22 15:50:20
【问题描述】:
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 的未定义方法“描述”

puts place.description
           ^~~~~~~~~~~

【问题讨论】:

  • 我喜欢你的编码设置
  • @LucaAngioloni 谢谢!强烈推荐适用于 Mac 的 Cathode 终端应用程序,带有 Alien 的声音(第一部电影)

标签: crystal-lang


【解决方案1】:

这样写:

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 用于授予对实例的读取属性的访问权限。 setter 用于设置。如果没有这个,编译器将尝试访问该方法,因为您没有授予对该属性的访问权限。

【讨论】:

  • 可以直接写getter description = "Default place"
猜你喜欢
  • 2021-07-17
  • 2017-08-28
  • 2018-09-05
  • 1970-01-01
  • 2019-08-30
  • 2012-05-23
  • 2021-11-01
  • 1970-01-01
  • 2021-09-02
相关资源
最近更新 更多