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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With