gpt4 book ai didi

ruby - Ruby 中的动态继承

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

我正在尝试制作一个类型非常灵活的 Ruby 类,并希望可以根据其初始化值从许多其他类继承属性:

class Test
def initialize(type,etc)
case type
when "stringio"
inherit_from_stringio_with_data(etc)
when "list"
inherit_from_enumerable_with_data(etc)
# and so on
end
end
end

Test.new("list").each do |item|
p item
end

s = Test.new("stringio")
s.seek(3)
puts s.read(2)

我知道 - 或者更确切地说已经读过 - mixin 的强大功能,但据我所知,它的布局并不完全正确。有没有人有任何想法,或者我正在尝试以其他方式最好地实现的东西(通过说 @content,其中包含 etc 作为 StringIO , 可枚举 等)。

谢谢!

最佳答案

module Stringy
def foo
puts "I am a stringy"
end
end

module Inty
def bar
puts "I am inty"
end
end


class Test
def initialize(mod_type)
self.extend(mod_type)
end
end


test = Test.new(Stringy)

关于ruby - Ruby 中的动态继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679615/

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