Is there a better way to get the public "properties" of a Ruby object?
def props
self.public_methods.grep(/.=$/) - ["==","==="]
end
Is there a better way to get the public "properties" of a Ruby object?
def props
self.public_methods.grep(/.=$/) - ["==","==="]
end
Your regular expression is incomplete: it matches methods that start in any character, rather than just word characters. The best way to get all the "writers" would be
methods.grep /^\w+=$/
And the regular expression can be shortened to
methods.grep /\w=$/
but is less clear.
In ruby, unless you do metaprogramming to break encapsulation, the only way to change an instance variable of another object is to call a method that happens to do so. And without using metaprogramming there's no way to tell what instance variable is being changed by a method.
For example, if I had a person, and that class had methods height_feet=
and height_meters=
in it, I wouldn't be able to tell if the implementation of that the person's height was based on @height_feet
or @height_meters
or even @height_cubits
.
This is a Good Thing, as it means you program purely to the interface, not the implementation.
Well, there is no such thing as a "property" in Ruby. And basically, since you made the word up (or more precisely: you made up its definition as it applies to Ruby), you get to define what it means, but on the flipside it also means you have to implement its semantics yourself.
So, if you define "property" to mean "method which ends with an equals sign but does not exclusively consist of equals signs", then, yes, your definition is the best possible way. (BTW: your definition of "property" includes methods such as <=
, >=
and !=
, which may or may not be what you want.)