3

我有以下代码用于将哈希集合转换为我的类上的方法(有点像活动记录)。我遇到的问题是我的二传手不工作。我对 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.
4

4 回答 4

8

如果您的目标是设置动态属性,那么您可以使用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)
于 2011-03-11T14:12:11.183 回答
4

您的 getter 方法始终返回原始哈希中的值。设置实例变量不会改变它;你需要让 getter 引用实例变量。就像是:

hash.each_pair do |key, value|
  define_method key do
    instance_variable_get("@#{key}")
  end
  # ... define the setter as before
end

你还需要在开始时设置实例变量,比如把

@properties.each_pair do |key,val|
  instance_variable_set("@#{key}",val)
end

在初始化方法中。

注意:我不保证这是最好的方法;我不是 Ruby 专家。但它确实有效。

于 2011-03-11T14:02:42.910 回答
2

它对我来说很好用(当然,在修复了代码中明显的语法错误之后):

myClass.instance_variable_get(:@property) # => nil
myClass.property = 42
myClass.instance_variable_get(:@property) # => 42

请注意,在 Ruby 中,实例变量始终是私有的,并且您永远不会为它们定义 getter,因此您实际上无法从外部(通过反射除外)查看它们,但这并不意味着您的代码不起作用,它仅表示您看不到它有效。

于 2011-03-11T14:07:49.090 回答
0

这基本上就是我对 method_missing 的建议。我对这两种方法都不够熟悉,无法说出为什么或为什么不使用它,这就是我上面问的原因。本质上,这将为您自动生成属性:

def method_missing sym, *args
   name = sym.to_s
   aname = name.sub("=","")

   self.class.module_eval do 
      attr_accessor aname
   end
  send name, args.first unless aname == name
end
于 2011-03-11T14:04:32.667 回答