何时使用define_singleton_method v define_method [英] When to use define_singleton_method v define_method
问题描述
在对此问题用户的一个答案中,mu也是简短地说,这说明您不希望对象的行为在初始化时发生太大的改变,这很有意义,您应该能够通过阅读对象的定义并进行内省来很好地推理出对象,但是我想到了这种情况:>
In one answer to this question user, mu is too short, explains that you wouldn't want an object's behavior to change too drastically on initialization, which makes sense, you should be able to reason about an object well by reading its definition and being introspective but I had this case in mind:
french_colors.yml
blue: blue
red: rouge
...
translations.rb
class Translations
def initialize(language: "french")
data = YAML.load_file("./translations/#{language}.yml")
data.each do |k, v|
define_method k do
v
end
end
print_french_colors
end
def print_french_colors
puts red
puts blue
end
end
初始化后,上述错误与
#=> NoMethodError: undefined method `define_method' for #<C:0x2efae80>
When initialized, the above Errors with
#=> NoMethodError: undefined method `define_method' for #<C:0x2efae80>
在这里,您将从翻译公司收到的文件中构建所有Translations行为,并希望将其作为实例,并且还希望它基于语言文件是动态的(这只是一个示例)
Here you build all of the Translations behavior off of the file received from a translation company and want it as an instance and also want it to be dynamic based on the language file (this is all just an example)
在初始化中将转换定义和设置为对象的属性,而不是像在OP和我试图做的那样在初始化中使用define_method,是否更有意义?还是编写方法define_singleton_method
来专门处理这种情况?
Would it make more sense to define and set the translations as attributes of the object in initialization instead of using define_method in initialization like this questions OP and I were trying to do? Or is it the case that the method define_singleton_method
was written to handle situations like this specifically?
如何在initialize()内部使用define_method
推荐答案
目前尚不清楚您的最终目标是什么.例如,如果语言不是法语,我不确定为什么会有print_french_colors
方法.看来您基本上是想读取yaml文件并使用它来设置一些预定义属性的值.
Its not clear what your final goal is. For example I am not sure why you would have a print_french_colors
method if the language were anything other than french. It seems like you basically want to read a yaml file and use that to set the value of some pre-defined attributes.
要做到这一点,我认为使用instance_variable_set而不是define_method会更有意义.这是一个例子.
To accomplish that, I think it would make more sense to use instance_variable_set rather than define_method. Here is an example.
french.yml
french.yml
blue: blue
red: rouge
require "yaml"
class Translations
attr_reader :blue, :red
def initialize(language: "french")
data = YAML.load_file("#{language}.yml")
data.each do |k, v|
if respond_to?(k)
instance_variable_set("@#{k}",v)
else
puts "#{k} is not defined"
end
end
print_french_colors
end
def print_french_colors
puts red
puts blue
end
end
t = Translations.new
t.print_french_colors
这篇关于何时使用define_singleton_method v define_method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!