我想创建一个类,在初始化此类的Object期间,将为其中一个变量赋值,这样就无法更改。 例如:
person = Person.new("Tom")
person.name #=> Tom
person.name = "Bob"
这应该引发错误或:
person.name #=> Tom -> still
答案 0 :(得分:2)
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
答案 1 :(得分:1)
我认为这会对您有所帮助: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