4 ms·
This is how Ruby works — you don't directly access an object's instance variables outside of the object, you call getter methods (commonly created with attr_rea
by chc 4y ago
This is how Ruby works — you don't directly access an object's instance variables outside of the object, you call getter methods (commonly created with attr_reader) or setter methods (commonly created with attr_writer, or attr_accessor). In this case, there is no setter. This is the same error you'd get if you tried to set a read-only attribute anywhere else.
- javawizard 4y agoAnd it's worth noting that, unlike with Python, this isn't Ruby internals letting an exception bubble up from somewhere; rather, `foo.bar = baz` is literally syntactic sugar for `foo.bar=(baz)`. (All Ruby operators work this way: something like `foo + bar` is short for `foo.+(bar)` for example.)
- yunohn 4y agoInteresting, so immutable is basically syntactic sugar for read-only on every attribute. That's a good backwards-compatible sort of implementation.
- faebi 4y agoOr ... you just ignore the rules john.instance_variable_set(:@name, "John Doe") john.send(:"instance_exec") do @name = "John Doe" end I love ruby.
- fknorangesite 4y agoHah, true. But good luck getting it past code review, right?
- JohnBooty 4y agoYeah. Non-Ruby devs are probably thinking, "what is the point of rules if the rules can be sidestepped so easily?" But IMO/IME Ruby strikes a good balance here. You can break the rules but it really sticks out like a sore thumb. We avoid these backdoors like the plague.
- chris12321 4y agoSharp knives and all that