使用send与OpenStruct

时间:2014-12-11 20:02:22

标签: ruby

我写了一个像这样的课:

class Query < OpenStruct
  def initialize(search)
    assign_attributes search
  end

  def assign_attributes(search)
    search.each do |k,v|
      puts "k #{k} v #{v}"
      send("#{k}=",v)
    end
  end
end

我希望能够做到以下几点:

e = Query.new( {a: "a", b: "b", c: "c"} )
e.a # => a
e.b # => b
e.c # => c

相反,这就是:

e = Query.new( {a: "a", b: "b", c: "c"} )
k a v a
NoMethodError: undefined method `[]=' for nil:NilClass

通常发送可以正常使用这样的动态分配。与OpenStruct有冲突吗?我可能做错了什么?

1 个答案:

答案 0 :(得分:3)

启用警告后,除错误外,我还会收到此警告:

/.../ruby/2.1.0/ostruct.rb:157: warning: instance variable @table not initialized

OpenStruct似乎需要自己进行一些初始化。

调用super()可以解决问题:

class Query < OpenStruct
  def initialize(search)
    super()
    assign_attributes search
  end

  # ...
end