gpt4 book ai didi

Ruby 从哈希创建方法

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

我有以下代码用于将散列集合转换为我的类的方法(有点像事件记录)。我遇到的问题是我的二传手不工作。我对 Ruby 还是很陌生,相信我已经让自己转过身来了。

class TheClass
def initialize
@properties = {"my hash"}
self.extend @properties.to_methods
end
end

class Hash
def to_methods
hash = self
Module.new do
hash.each_pair do |key, value|
define_method key do
value
end
define_method("#{key}=") do |val|
instance_variable_set("@#{key}", val)
end
end
end
end
end

方法已创建,我可以在类里面阅读它们,但设置它们不起作用。

myClass = TheClass.new
item = myClass.property # will work.
myClass.property = item # this is what is currently not working.

最佳答案

如果您的目标是设置动态属性,那么您可以使用 OpenStruct .

require 'ostruct'

person = OpenStruct.new
person.name = "Jennifer Tilly"
person.age = 52

puts person.name
# => "Jennifer Tilly"
puts person.phone_number
# => nil

它甚至内置支持从哈希创建它们

hash = { :name => "Earth", :population => 6_902_312_042 }
planet = OpenStruct.new(hash)

关于Ruby 从哈希创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5273551/

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