English 中文(简体)
我怎么能给某个特定情况增添新的属性?
原标题:How can I add new attributes to a particular instance?

我怎么能给某个特定情况增添新的属性?

For example here I want to add attr_acessors methods to attributes "m1","m2" in object e1 and "m4".."m6" to e2

e1=Element.new("e1",["m1","m2"])
e2=Element.new("e2",["m4","m5","m6"])
e1.m1 = "try"
puts e2.m4

To allow this :

class Element
  attr_accessor :name
  def initialize name,meths=[]
    @name=name
    meths.each do |m|
      #?? 
    end
  end
end
最佳回答

为此:

meths.each do |m|
  singleton_class().class_eval do
    attr_accessor m
  end
end

在<代码>singleton_}()方法下定义如下:

def singleton_class
  class << self
    self
  end
end

(可能希望将其变成私人)。

这样做只会在具体情况下而不是在要素类别上产生出入口。

问题回答

为什么不使用简单的开放标准?

require  ostruct 
e1 = OpenStruct.new
e1.m1 =  try 

Alternatively, you can add attribute to any object using:

a.instance_eval( def m2; @m2; end; def m2=(x); @m2=x;end )

如果你想增加特定类别的所有特性,你也可以:

a.class.instance_eval( attr_accessor :mmm )

Here is a simpler solution:

methods.each do |method|
 class << self
  attr_accessor method
 end
end

这样,你就可以删除额外方法定义和<代码>_eval。 由于<条码>等;及 ;自封已把你置于单子方法的单子类别的范围。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签