如何通过它的 "actual" class 找到一个实例变量?

How do I find a instance variable through its "actual" class?

我正在编写的程序将元素存储在类型为 Position => LivingBeing | Thing 的名为 grid 的散列中。这个 grid 存储在 Map 上,我希望这个 Map 到 return class Apple 的元素的位置是Thing.

的子class

但是,当使用 typeof() 获取 class 时,我得到 LivingBeing | Thing 而不是子 class Apple

这里是 Map class:

class Map
  @@grid = {} of Position => LivingBeing | Thing

  def initialize()
  end

  # Add an entity to the grid
  def add_entity(new_entity : LivingBeing | Thing)
    @@grid[new_entity.position] = new_entity
  end

  # Return the position of an object of class "something"
  def self.where_is?(something : Class)
    # First attempt was to get the key by the value
    # @@grid.key(something)

    @@grid.each do |position, thing|
      # Returns "thing #<Apple:0x55f1772085c0> at Position(@x=1, @y=2) is (LivingBeing | Thing)"
      puts "thing #{thing} at #{position} is #{typeof(thing)}"
      position if typeof(thing) == something
    end
  end

这里是Thingclass:

abstract class Thing
  getter position
  @name = "Unkown object"

  def initialize(@position : Position)
  end
end

class Apple < Thing
  @name = "Apple"
end

这里是 Position 结构:

struct Position
  getter x, y

  def initialize(@x : Int32, @y : Int32)
  end
end

这是我试图让它通过的测试:

it "gives a random thing location based on its class" do
  world = Map.new()
  apple = Apple.new(Position.new(1, 2))
  puts "Apple type : #{typeof(apple)}" # Returns "Apple type : Apple"
  world.add_entity(apple)
  position = Map.where_is?(Apple)
  position.should eq Position.new(1, 2)
end

是否有一些 class 方法或函数可以提供 Apple class? 还是设计问题?

感谢您的回答!

我有一个解决方案是我的功能:

  # Return the position of an object of class "something"
  def self.where_is?(something)
    @@grid.each do |position, thing|
      return position if thing.is_a?(typeof(something))
    end
  end

这是为了测试:

  it "gives a random thing location" do
    world = Map.new(4)
    apple = Apple.new(Position.new(1, 2))
    world.add_entity(apple)
    position = Map.where_is?(Apple.new(Position.new(0, 0)))
    position.should eq Position.new(1, 2)
  end

没有别的办法我就这样用了。但我更希望能够直接搜索 class Apple 而不是创建 Apple

的实例

我希望能够 position = Map.where_is?(Apple) 而不是 position = Map.where_is?(Apple.new(Position.new(0, 0)))

正如@RX14所说,看起来你想检查运行时间"type",即.class。这是一个例子:

class Apple
  @name = "Apple"
end

def check(obj : Object)
  obj.class == Apple
end

a=Apple.new
p check(a)

你可以使用forall来解决这个问题:

  # Return the position of an object of class "something"
  def self.where_is?(something : T.class) forall T
    @@grid.each do |position, thing|
      return position if thing.is_a?(T)
    end
  end

并根据需要使用 Map.where_is? Apple 调用它。

这是有效的,因为类型变量 T(使用 forall T 引入)可以从传入与 [= 匹配的常量 Apple 推断为 Apple 17=] 类型限制。 T 是一个常量,您可以将其与 is_a?.

一起使用