On Mon, 29 Jan 2001, Johann Hibschman wrote:

> Hi folks,
> 
> I'm a long-time python-head, just playing with Ruby for fun, and I was
> wondering if there was anything in Ruby similar to the __getattr__
> special method in Python.

It sounds like what you want is method_missing: 

class ObjMirror
	@@meths = [:x, :y, :name, :state]
 
	def initialize(obj)
		@obj = obj
	end

	def method_missing(method, *args)
		if @@meths.include? method
			...
		end
	end
end

> 
> __getattr__ is called whenever there is an attempt to look up an
> attribute that fails.  I use it to implement wrappers over C-objects
> in a concise manner when performance isn't important, such as in:
> 
> class ObjMirror:
>   meths = ["x", "y", "name", "state"]
>   def __init__(self, obj):
>      self.obj = obj
>   def __getattr__(self, attr):
>     if attr in self.meths:
>       fcn_name = "obj_get_"+attr
>       return (getattr(obj_module, fcn_name))(self.obj)
> 
> That's just one example.  It comes up every now and then.  Is Ruby
> too disciplined for this, or is there a way around that?
> 
> --Johann
> 
> -- 
> Johann Hibschman                           johann / physics.berkeley.edu
>