问题
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