gpt4 book ai didi

ruby - 如何做真正的只读属性(accessors => attributs)

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:28 25 4
gpt4 key购买 nike

考虑这个简单的代码:

class Yeah
attr_reader :foo
attr_reader :fool
attr_reader :feel
def initialize(foo: "test", fool: {}, feel: [])
@foo = foo
@fool = fool
end
end

test = Yeah::new
pp test
test.fool[:one] = 10
pp test

输出:

#<Yeah:0x000008019a84a0 @foo="test", @fool={}>
#<Yeah:0x000008019a84a0 @foo="test", @fool={:one=>10}>

我的问题是,有一种“简单”、“干净”的方法,可以对真正的只读数组、哈希属性进行读取访问,或者我需要继承数组或哈希,并带有很多难以编写的锁定,(undef,别名)或使用代理、委托(delegate)或其他像这样的模式?

最佳答案

你可以这样想:

class Yeah
def self.reader_meth
%i(foo fool feel).each do |m|
define_method(m){instance_variable_get("@#{m}").dup.freeze}
end
end
def initialize(foo: "test", fool: {}, feel: [])
@foo = foo
@fool = fool
@feel =feel
end
reader_meth
end

test = Yeah.new
test # => #<Yeah:0x8975498 @foo="test", @fool={}, @feel=[]>
test.fool[:one] = 10 # can't modify frozen Hash (RuntimeError)
test # => #<Yeah:0x8975498 @foo="test", @fool={}, @feel=[]>

关于ruby - 如何做真正的只读属性(accessors => attributs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com