开发者

How can I tell if a method is read-write, read-only, or write-only, via introspection?

I am coming from Java, and want to know if I can 'set' an instance variable for an object using introspection.

For example, if I have the following class declaration, with the two instance variables, first_attribute and second_attribute:

class SomeClas开发者_开发技巧s  
  attr_accessor :first_attribute
  attr_reader :second_attribute

  def initialize()  
    # ...
  end
end

I want to be able to get the instance methods, presumably by calling SomeClass.instance_methods and know which of those instance methods are read/write vs. just read-only.

In Java I can do this by:

PropertyDescriptor[] properties = PropertyUtils.GetPropertyDescriptors(SomeClass);
for (prop : properties) {
  if (prop.getWriteMethod() != null) {
    //  I can set this one!
  }
}

How do I do this in Ruby?


There's not really anything built-in like the Java property stuff, but you can do it pretty easily like this:

self.class.instance_methods.grep(/\w=$/)

Which will return the names of all the setter methods on the class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜