meso_2600 meso_2600 - 1 month ago 12
Ruby Question

How make a variable public final in Ruby

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

Answer
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
Comments