Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading