gpt4 book ai didi

ruby - 在 Struct 实例中创建动态属性

转载 作者:数据小太阳 更新时间:2023-10-29 07:18:25 24 4
gpt4 key购买 nike

是否可以在Struct 实例中动态创建属性?

class Person < Struct.new(:name)
end

p = Person.new("Bilbo")
p[:surname] = "Jenkins" # does not work

最佳答案

您可以使用 OpenStruct:

require 'ostruct'

p = OpenStruct.new(name: "Bilbo")
p[:surname] = "Jenkins"

p.surname # => "Jenkins"

关于ruby - 在 Struct 实例中创建动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27700226/

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