如何将变量的值赋给常量?

时间:2022-10-26 21:00:05

Writing an assignment such as CONST = some_var will raise SyntaxError as Constant in ruby could not be reassigned.

编写CONST = some_var之类的赋值将引发SyntaxError,因为ruby中的Constant无法重新分配。

But in some cases, I want to hold the current variable's value in a constant and lock it there.

但在某些情况下,我想将当前变量的值保存在常量中并将其锁定在那里。

For example, when I initialize an instance from a class, I want to lock the passed in value within the instance. How should I do it the right way in ruby? (following is a illegal code in ruby trying to realize it, you get the idea)

例如,当我从类初始化实例时,我想锁定实例中的传入值。我应该如何在红宝石中以正确的方式做到这一点? (以下是ruby试图实现它的非法代码,你明白了)

class SomeClass
  def initialize(status)
    STATUS = status # it is illegal now
  end
end

2 个解决方案

#1


2  

The Ruby constants are expected to preserve the same value, it's a recommendation, not a must:

Ruby常量应该保留相同的值,这是一个建议,而不是必须:

A Ruby constant is like a variable, except that its value is supposed to remain constant for the duration of the program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant.

Ruby常量就像一个变量,除了它的值应该在程序的持续时间内保持不变。 Ruby解释器实际上并不强制执行常量的常量,但如果程序更改常量的值,它会发出警告。

#2


1  

Use an instance variable with a getter and no setter. Like this:

将实例变量与getter一起使用,不使用setter。喜欢这个:

class SomeClass
  attr_reader :status
  def initialize(status)
    @status = status
  end
end

Now you can use your object like this:

现在您可以像这样使用您的对象:

>> a = SomeClass.new(5)
=> #<SomeClass:0x108c80218 @status=5>
>> a.status
=> 5
>> a.status=7
NoMethodError: undefined method `status=' for #<SomeClass:0x108c80218 @status=5>
from (irb):9

#1


2  

The Ruby constants are expected to preserve the same value, it's a recommendation, not a must:

Ruby常量应该保留相同的值,这是一个建议,而不是必须:

A Ruby constant is like a variable, except that its value is supposed to remain constant for the duration of the program. The Ruby interpreter does not actually enforce the constancy of constants, but it does issue a warning if a program changes the value of a constant.

Ruby常量就像一个变量,除了它的值应该在程序的持续时间内保持不变。 Ruby解释器实际上并不强制执行常量的常量,但如果程序更改常量的值,它会发出警告。

#2


1  

Use an instance variable with a getter and no setter. Like this:

将实例变量与getter一起使用,不使用setter。喜欢这个:

class SomeClass
  attr_reader :status
  def initialize(status)
    @status = status
  end
end

Now you can use your object like this:

现在您可以像这样使用您的对象:

>> a = SomeClass.new(5)
=> #<SomeClass:0x108c80218 @status=5>
>> a.status
=> 5
>> a.status=7
NoMethodError: undefined method `status=' for #<SomeClass:0x108c80218 @status=5>
from (irb):9