我正在编写的程序将元素存储在名为 grid
的哈希中,其类型为 Position => LivingBeing |事情
。此网格
存储在Map
上,我希望此Map
返回Apple
类元素的位置> 它是 Thing
的子类。
但是,当使用 typeof()
获取类时,我得到 LivingBeing | Thing
而不是子类 Apple
这是Map
类:
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
这里是 Thing
类:
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
是否有一些类方法或函数可以提供 Apple
类?
还是设计问题?
谢谢您的回答!
最佳答案
您可以使用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? 调用它苹果
正如你所愿。
这是可行的,因为类型变量 T
(使用 forall T
引入)可以通过传入常量 推断为
匹配 Apple
>AppleT.class
类型限制。 T
是一个常量,可以与 is_a?
一起使用。
关于class - 如何通过 "actual"类找到实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47982006/