From: dblack@... Date: 2006-05-04T16:00:23+09:00 Subject: Re: Ruby idiom for attributes / properties Hi -- On Thu, 4 May 2006, John Lam wrote: > On 5/4/06, James Britt wrote: >> >> What would you consider to be an attribute? > > > I'm just borrowing the ActiveRecord terminology for attributes. In my mind, > an attribute == a property. In .NET, a property is a bit of syntactical > sugar (but also a distinct metadata entity) for a getter and setter method. > > Consider this bit of C# code: > > class Foo { > public string StringProperty { > get { return "string"; } > set { Console.WriteLine("setting a string to " + value); } > } > } > > This generates under the covers a get_StringProperty and a > set_StringProperty method. > > I would consider it equivalent to this Ruby code: > > class Foo > def string_property > 'string' > end > def string_property=(value) > puts "setting a string to #{value}" > end > end > > The problem is that I can't distinguish a string_property method from any > other method. Why is that a problem? :-) It does demonstrate, though, that the C# and Ruby samples are not equivalent. > In .NET, I can walk the property metadata to discover all of > those properties (and those are things that can be bound to data-aware > controls in the framework). In general, the equivalent of a method name with the general format get_x_property in Ruby is x, and the equivalent of set_x_property in Ruby is x=. There's room for debate as to whether there's really such a thing as an "attribute" at the language level at all in Ruby; I tend to think not, or very nearly not, since the only support for the concept, other than the method mechanisms that are in the language anyway, are the attr_* methods, and to my eyes those are just convenience methods layered on top of the language. (Then again, they are in the language; hence the debate :-) David -- David A. Black (dblack@wobblini.net) * Ruby Power and Light, LLC (http://www.rubypowerandlight.com) > Ruby and Rails consultancy and training * Author of "Ruby for Rails" from Manning Publications! > Paper version coming in early May! http://rubyurl.com/DDZ