Static variables in ruby, like in C functions

前端 未结 6 1643
花落未央
花落未央 2021-01-22 08:29

Is there any such thing as static variables in Ruby that would behave like they do in C functions?

Here\'s a quick example of what I mean. It prints \"6\\n7\\n\" to the

6条回答
  •  花落未央
    2021-01-22 09:05

    Use a variable in the singleton class (The static class itself)

    class Single
      def self.counter
        if @count  
          @count+=1
        else
          @count = 5
        end
      end
    end
    

    In ruby, any class is an object which has only one instance. Therefore, you can create an instance variable on the class, and it will work as a "static" method ;)

    Output:

      ruby 2.5.5p157 (2019-03-15 revision 67260) [x86_64-linux]
    
    => :counter
       Single.counter
    => 5
       Single.counter
    => 6
       Single.counter
    => 7
    

    To get this behaviour on the main scope, you can do:

    module Countable
      def counter
        if @count  
          @count+=1
        else
          @count = 5
        end
      end
    end
    
    => :counter
       self.class.prepend Countable # this "adds" the method to the main object
    => Object
       counter
    => 5
       counter
    => 6
       counter
    => 7
    

提交回复
热议问题