gpt4 book ai didi

ruby - 将散列转换为结构

转载 作者:数据小太阳 更新时间:2023-10-29 06:22:37 26 4
gpt4 key购买 nike

如何在 ruby​​ 中将散列转换为结构?

鉴于此:

h = { :a => 1, :b => 2 }

我想要一个这样的结构:

s.a == 1
s.b == 2

最佳答案

如果您已经定义了一个结构,并且您想要使用散列实例化一个实例:

Person = Struct.new(:first_name, :last_name, :age)

person_hash = { first_name: "Foo", last_name: "Bar", age: 29 }

person = Person.new(*person_hash.values_at(*Person.members))

=> #<struct Person first_name="Foo", last_name="Bar", age=29>

关于ruby - 将散列转换为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11962192/

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