Search code examples
selfcrystal-lang

How to return self in Crystal


I'm a newbie in Crystal.

I'm trying to return self in Crystal, like in this Python:

class Something:
    def some_method():
        # do something
        return self

Solution

  • Here is a little extended example. say_hello is called by self.say_hello. Just defining self returns the object/instance itself, like expected.

    % cat file.cr
    class Something
      def say_hello
        puts "Hi"
      end
    
      def some
        self.say_hello
      end
    
      def some_method
        self
      end
    end
    
    s = Something.new
    
    s.some
    
    puts s.some_method
    

    Output

    % crystal run file.cr
    Hi
    #<Something:0x102b6de80>