gpt4 book ai didi

ruby - 在 Ruby 模块中继承常量

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

在 Ruby 中,我正在尝试创建一个类,该类基于初始化期间给出的值,将从以下模块之一继承。我想创建一个基本模块,这两个模块都继承自该模块,其中包含使用继承它的模块中定义的常量的常用方法。示例:

module BaseMod
def what_am_i
puts OUTPUT
end
end

module Tall
OUTPUT = "I am tall"
include BaseMod
end

module Short
OUTPUT = "I am short"
include BaseMod
end

class Person
def initialize type
if type =~ /short/i
extend Short
else
extend Tall
end
end
end

p = Person.new "short"
p.what_am_i

我的问题是,当调用“p.what_am_i”时出现以下错误:

NameError: uninitialized constant BaseMod::OUTPUT
const_missing at org/jruby/RubyModule.java:2642
what_am_i at test_logic2.rb:3
(root) at test_logic2.rb:28

我也想知道是否有更好的方法来做到这一点。

最佳答案

module BaseMod
def what_am_i
puts self.class::OUTPUT
end
end

module Tall
OUTPUT = "I am tall"
include BaseMod
end

module Short
OUTPUT = "I am short"
include BaseMod
end

class Person
def initialize(type)
if type =~ /short/i
self.class.send(:include, Short)
else
self.class.send(:include, Tall)
end
end
end

p = Person.new "short"
p.what_am_i

编辑:上面的代码实际上不起作用:

p = Person.new "short"
p.what_am_i
>> I am short
p = Person.new "tall"
p.what_am_i
>> I am tall
p = Person.new "short"
p.what_am_i
>> I am tall

这是另一种尝试:

module BaseMod
def self.included(base)
base.send(:define_method, :what_am_i) do
puts base::OUTPUT
end
end
end

module Tall
OUTPUT = "I am tall"
include BaseMod
end

module Short
OUTPUT = "I am short"
include BaseMod
end

class Person
def initialize type
if type =~ /short/i
extend Short
else
extend Tall
end
end
end

p = Person.new "short"
p.what_am_i
p = Person.new "tall"
p.what_am_i
p = Person.new "short"
p.what_am_i

关于ruby - 在 Ruby 模块中继承常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514353/

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