プログラムはタイプPosition => LivingBeing | Thing
のgrid
と呼ばれるハッシュの要素を記憶しています。このgrid
はMap
に保存されていると私は、このMap
がThing
のサブクラスであるクラスApple
の要素の位置を返すようにしたいと思います。"実際の"クラスでインスタンス変数を見つけるにはどうすればよいですか?私が書いている
しかし、クラスを取得するために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
クラスを与えることができるいくつかのクラスメソッドや関数はありますか? それはデザイン上の問題ですか?
は、あなたの答えをありがとう!私が持っている
あなたのコードをコンパイルするのに 'Position'が必要ですが、' thing.is_aならpositionを返しますか?何かがあなたの問題を解決する? 'typeof(foo)'はコンパイル時の型を返しますが、 'foo.is_a?'と 'foo.class'は実行時に動作します。 – RX14
コードをコンパイルする場合は、私の質問を更新して 'Position'を追加しました。私は 'positionof thing.is_a(something) 'と' typeof(thing)== something'の位置を置き換えようとしましたが、このエラーが発生します: '' CONST' – KillianKemps