How make a variable public final in Ruby

江枫思渺然 提交于 2019-12-11 10:38:32

问题


I would like to create a class that during initialization of an Object of this class would assign provided value to one of the variables, in such way it can't be changed. For example:

person = Person.new("Tom")
person.name  #=> Tom
person.name = "Bob"

this should raise an error or:

person.name #=> Tom -> still

回答1:


class Person
  def initialize name
    @name = name
  end
  attr_reader :name
end

person = Person.new("Tom")
person.name         #=> Tom
begin
  person.name = "Bob"
rescue
  puts $!.message   # => Undefined method error
end
person.name         #=> Tom



回答2:


I think this will help you : static variables in ruby

class Foo
 @@foos = 0

 def initialize
 @@foos += 1
 end

 def self.number_of_foos
 @@foos
 end
end

Foo.new
Foo.new
Foo.number_of_foos #=> 2


来源:https://stackoverflow.com/questions/18167614/how-make-a-variable-public-final-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!