From: Trans Date: 2005-10-31T12:12:07+09:00 Subject: Re: C# attributes in Ruby? zdennis wrote: > Stephan Mueller wrote: > > Hi, > > > > sorry if this has been discussed before (in this case please point me in > > the right direction :). I am wondering if there is a mechanism in Ruby to > > get something as C# does with its attributes. In C# attributes are a way > > to tag namespaces, classes, methods etc. with metadata which can be quite > > usefull in combination with reflection. > > > > exmpl: > > > > ... > > [SomeFancyAttribute(EvenMoreFancyValue)] > > public int GetValue() > > { > > ... > > } > > > > This would associate the attribute SomeFancyAttribute with its value > > EvenMoreFancyValue with (to?) the method GetValue. Later this information > > could be retrieved via reflection and used for whatsoever. > > > > Is there a way to achieve something comparable with ruby? > > > > > > Thanks for your thoughts! > > Steph, > > I am trying to see where you would use? Is the below example valid of how-you would use it? > > arr = [ obj1, obj2, obj3, obj4 ] > arr.each do |x| > puts obj1.value if obj1.ann.fancy_attribute =~ /fancy_value/ > end > > OR > > fancy_objects = 0 > ObjectSpace.each_object{ |obj| fancy_objects += 1 if obj.ann.fancy_attribute =~ /fancy_value } > puts "YOu had #{fancy_object} fancy objects" > Yes. That's about right. Keep in mind though that #ann works differently for classes and modules than it does for other objects b/c it is used for method annotations in those cases. So use #annotation instead in this last example. I may change #ann for objects to reflect the same functionality so there won't be any possible confusio. I suppose obj#ann could apply to singleton methods --but I'm not sure yet. T.