From: Daniel Schierbeck Date: 2005-12-19T22:07:47+09:00 Subject: Re: How to know if a method is read-write or read-only Trans wrote: > I've now come across a second usecase for knowing if a method is > read-write or read-only on it's object's state. Both cases boil-down to > having meta-method behave differently depending on the behavior of > method being delegated to, but the circumstances differ completely. To > give an example, the current case generates method wraps for any given > class, applying thread sycronization. If a method is read-only it's > wraped in a Sync::SH, if read-write then Sync::Ex. > > So I wonder, is there a way to determine this fact about a method? > > Thanks, > T. > Do you want to know if a method changes its object's state? In that case, you could duplicate the object, freeze the duplicate and try to call the method. If an Exception is raised, then either the method has a bug or it is state-changing. class Object def changes_state?(method) self.dup.freeze.send(method) return false rescue TypeError return true end end "foo".changes_state? :upcase => false "foo".changes_state? :upcase! => true It would be nice if a special exception was thrown when attempting to call a method on a frozen object, so that you could distinguish it from the usual TypeErrors. Note that this method isn't very efficient, since it duplicates the entire object on each invocation. If you were to check many methods on a single object, you might want to keep the frozen duplicate in an instance variable. Cheers, Daniel