How to I make private class constants in Ruby

前端 未结 4 1255
执笔经年
执笔经年 2021-02-01 12:49

In Ruby how does one create a private class constant? (i.e one that is visible inside the class but not outside)

class Person
  SECRET=\'xxx\' # How to make clas         


        
4条回答
  •  旧时难觅i
    2021-02-01 13:42

    Instead of a constant you can use a @@class_variable, which is always private.

    class Person
      @@secret='xxx' # How to make class private??
    
      def show_secret
        puts "Secret: #{@@secret}"
      end
    end
    Person.new.show_secret
    puts Person::@@secret
    # doesn't work
    puts Person.class_variable_get(:@@secret)
    # This does work, but there's always a way to circumvent privateness in ruby
    

    Of course then ruby will do nothing to enforce the constantness of @@secret, but ruby does very little to enforce constantness to begin with, so...

提交回复
热议问题