1

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
Ozymandias
  • 2,533
  • 29
  • 33
meso_2600
  • 1,940
  • 5
  • 25
  • 50
  • 2
    Sounds like you're talking about "final" variables, which doesn't exist in Ruby. But take a look at this: http://stackoverflow.com/questions/2441524/closest-ruby-representation-of-a-private-static-final-and-public-static-final – superEb Aug 11 '13 at 00:34
  • 2
    Why are you defining `name=` on Person in the first place if you don’t want it? – Andrew Marshall Aug 11 '13 at 02:56
  • That was an example in case someone tried to set it again and I'd like to prevent it – meso_2600 Aug 11 '13 at 18:22

2 Answers2

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
sawa
  • 165,429
  • 45
  • 277
  • 381
1

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
Community
  • 1
  • 1
Zz Oussama
  • 229
  • 1
  • 12