gpt4 book ai didi

ruby - 在 Ruby 中创建 Expando 对象

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

有没有更好的方法来编写这个 Expando 类?它的编写方式不起作用。我正在使用 Ruby 1.8.7

起始代码引用自https://gist.github.com/300462/3fdf51800768f2c7089a53726384350c890bc7c3

class Expando
def method_missing(method_id, *arguments)
if match = method_id.id2name.match(/(\w*)(\s*)(=)(\s*)(\.*)/)
puts match[1].to_sym # think this was supposed to be commented
self.class.class_eval{ attr_accessor match[1].to_sym }
instance_variable_set("#{match[1]}", match[5])
else
super.method_missing(method_id, *arguments)
end
end
end

person = Expando.new
person.name = "Michael"
person.surname = "Erasmus"
person.age = 29

最佳答案

最简单的写法就是根本不写! :) 请参阅 OpenStruct类,包含在标准库中:

require 'ostruct'

record = OpenStruct.new
record.name = "John Smith"
record.age = 70
record.pension = 300

不过,如果我要写的话,我会这样做:

# Access properties via methods or Hash notation
class Expando
def initialize
@properties = {}
end
def method_missing( name, *args )
name = name.to_s
if name[-1] == ?=
@properties[name[0..-2]] = args.first
else
@properties[name]
end
end
def []( key )
@properties[key]
end
def []=( key,val )
@properties[key] = val
end
end

person = Expando.new
person.name = "Michael"
person['surname'] = "Erasmus"
puts "#{person['name']} #{person.surname}"
#=> Michael Erasmus

关于ruby - 在 Ruby 中创建 Expando 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4703642/

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