Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to get the public "properties" of a Ruby object?

Is there a better way to get the public "properties" of a Ruby object?

def props
  self.public_methods.grep(/.=$/) - ["==","==="]
end
like image 548
BuddyJoe Avatar asked Dec 31 '25 01:12

BuddyJoe


2 Answers

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.

like image 95
Aaa Avatar answered Jan 02 '26 15:01

Aaa


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.

like image 21
Andrew Grimm Avatar answered Jan 02 '26 14:01

Andrew Grimm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!