Static variables in ruby, like in C functions

前端 未结 6 1646
花落未央
花落未央 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:00

    Scope your variable in a method and return lambda

    def counter
      count = 0
      lambda{count = count+1}
    end
    
    test = counter
    test[]
    #=>1
    test[]
    #=>2
    

提交回复
热议问题