5 ms·
I find it odd that getters and setters are implemented in Ruby … manually. attr_accessor is the idiomatic way to do it (or attr_reader / attr_writer if you want
by drewbug01 4y ago
I find it odd that getters and setters are implemented in Ruby … manually. attr_accessor is the idiomatic way to do it (or attr_reader / attr_writer if you want more granular control).
- chrisseaton 4y agoIt's for encapsulation. You can switch them out for a method with logic without changing your interface. I don't know Python very well - is that the same there?
- syntaxfree 4y agoYou can override the relevant dunders, but why would you.
- chrisseaton 4y ago> but why would you To migrate an API - that's what I said.
- drewbug01 4y agoApologies - I mean “the author implemented their getters / setters in the ruby example by writing actual methods by hand. The idiomatic way to do it in ruby is to simply write: “attr_accessor :title”. There’s no change in interface needed in the ruby example if you decide that you want to replace that with fully-written getter/setter methods like the post shows; attr_accessor generates exactly those same signatures for you.
- Nullabillity 4y agoYes, you can replace attributes with properties without changing the consuming code. For example: >>> class Foo: ... @property ... def bar(self): ... return "hello from a property" ... @bar.setter ... def bar(self, value): ... print(f"tried to replace bar with {value}") >>> Foo().bar 'hello from a property' >>> Foo().bar = "asdf" tried to replace bar with asdf
- chrisseaton 4y agoI know it's completely subjective and intellectually irrelevant, but wow I think those annotations are super ugly. In Ruby it's all just method calls - properties, methods, user control-flow, everything.
- jefftk 4y agoIt's all just method calls in python too! @foo def bar(): ... Is just syntactic sugar for: def bar(): ... bar = foo(bar)
- remram 4y agoIt's a bit of a weird take when attribute definition in Ruby also uses at signs specifically. Which part do you find ugly?
- chrisseaton 4y ago> It's a bit of a weird take when attribute definition in Ruby also uses at signs specifically. No that’s instance variables. > Which part do you find ugly? In Ruby to modify a method you just call a method. I guess I think a second, redundant, way to call methods is not elegant.
- rat87 4y agoIn Ruby if else is not a method for some reason also blocks are not objects for some reason "seems inelegant"
- chrisseaton 4y ago> In Ruby if else is not a method for some reason This is because there’s not a good way to pass two delayed computations - two blocks. Looping constructs were replaced by method variants. > also blocks are not objects for some reason Yeah they’re reifiable but not sure why not reified by default.