Is there a way to get any variable from a Crystal class?

70 Views Asked by At

In a Crystal class with some instance vars:

class Coordinate
    def initialize(x : Int32, y : Int32)
        @x = x
        @y = y
    end
end

In order to access said vars, you'd need to write methods like this:

...
    def x
        @x
    end

That is fine in this example, but can be very tedious and time consuming if you have lots of vars which you need to access. Is there a way to generally access any variable of a class?

I did think of trying to find an equivalent to ruby's eval() but since Crystal is compiled there obviously isn't much to work with.

An ideal solution would do something like this:

...
    def get(var)
        @var
    end
1

There are 1 best solutions below

0
pmf On BEST ANSWER

The Crystal Standard Library provides macros which simplify the definition of getter and setter methods:

Use property for read/write access, or getter for read-only access:

class Coordinate
    property x
    getter y

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

point = Coordinate.new 10, 20

point.x = 30

puts point.x
puts point.y
30
20