3 ms·
Zork-alikes aside... I'm looking for practical applications :) I recently re-watched Yaron Minsky's "Effective ML" talk where (towards the end) he talks about
by zwp 11y ago
Zork-alikes aside... I'm looking for practical applications :)
I recently re-watched Yaron Minsky's "Effective ML" talk where (towards the end) he talks about making read-only and read-write types. That's where I thought Jamis was going with the state machine example: one could tell an object "yo, make yourself immutable!" (ie redefine your methods so that you can't change yourself). But in an OO world that seems more neatly achieved with subclassing. [To the extent of faking anything "immutable" in ruby"].
There's #freeze I suppose... and no #unfreeze. Which is perhaps sensible :) And #freeze only guards against new assignment to instance variables; it doesn't guard against an instance method mutating the content of an instance variable (def esquirify! ; @name << ' Esq.' ; end). So there's that. But I'm far from convinced...
Python has this "inner-methods" capability (with saner scoping) which is a great antidote for python's limited lambdas. But that's not a problem with ruby.
It's a neat trick (and nice to read something from Jamis again). Are there any sensible use cases?
- netghost 11y agoOne use might be to create simple singletons. That said, I'm not entirely sure how you would do it, maybe have `Object#initialize` redefine `Object#new` to always return the singleton.
- netghost 11y agoYup, here's how to use it to define a Singleton that is transparent to the caller: class S class << self attr_accessor :singleton end attr_accessor :value def initialize @value = "xxx" S.singleton = self def S.new S.singleton end end end a = S.new # => #<S:0x007ff4a41532e0 @value="xxx"> b = S.new #=> #<S:0x007ff4a41532e0 @value="xxx"> a.value = "zzz" b.value # "zzz" a.object_id == b.object_id #=> true That said... doing this may win you great sorrow.