0

我有一个班级样本

Sample.class 返回

(id :integer, name :String, date :date)

并且哈希将所有给定的属性作为其键。那么如何在不独立分配每个属性的情况下初始化 Sample 的变量。

就像是

Sample x = Sample.new

x.(attr) = Hash[attr]

如何遍历属性,问题是哈希包含不属于类属性的键

4

3 回答 3

1

看看这篇关于对象初始化的文章。你想要一个initialize方法。

编辑你也可以看看这个关于设置实例变量的帖子,我认为这正是你想要做的。

于 2012-06-13T01:17:57.743 回答
1
class Sample
  attr_accessor :id, :name, :date
end

h = {:id => 1, :name => 'foo', :date => 'today', :extra1 => '', :extra2 => ''}

init_hash = h.select{|k,v| Sample.method_defined? "#{k}=" }

# This will work
s = Sample.new
init_hash.each{|k,v| s.send("#{k}=", v)}

# This may work if constructor takes a hash of attributes
s = Sample.new(init_hash)
于 2012-06-13T02:05:58.470 回答
0

试试这个:

class A
  attr_accessor :x, :y, :z
end

a = A.new
my_hash = {:x => 1, :y => 2, :z => 3, :nono => 5}

如果您没有可以从哈希分配的属性列表,您可以这样做:

my_attributes = (a.methods & my_hash.keys)

使用a.instance_variable_set(:@x = 1)语法赋值:

my_attributes.each do |attr|
  a.instance_variable_set("@#{attr.to_s}".to_sym, my_hash[attr])
end

注意(感谢 Abe):这假设所有要更新的属性都有 getter 和 setter,或者任何只有 getter 的属性在 my_hash 中没有键。

祝你好运!

于 2012-06-13T05:06:36.957 回答