如何在Ruby中将变量设为public final [英] How make a variable public final in Ruby

查看:94
本文介绍了如何在Ruby中将变量设为public final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类,该类在初始化该类的对象时会将提供的值分配给其中一个变量,这样就不能更改它. 例如:

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

推荐答案

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

这篇关于如何在Ruby中将变量设为public final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆