Bug #19257
closedData that defines a member called hash
Description
I believe this should raise an error given that Data#hash
exists as a pre-defined core method and serves a very specific purpose:
data = Data.define(:hash)
obj = data.new(hash: "foo")
obj.hash
# => "foo"
An alternative would be to make obj[:hash]
return the value of the member and obj.hash
would return the hash of the object, but that could be confusing.
Updated by nobu (Nobuyoshi Nakada) almost 2 years ago
- Status changed from Open to Feedback
Always you can override methods defined in super classes.
class C
end
obj = C.new
p obj.hash #=> an integer
class C
def hash = "foo"
end
p obj.hash #=> "foo"
No #[]
method is a significant difference from Struct
.
Updated by ufuk (Ufuk Kayserilioglu) almost 2 years ago
While I understand the potential for confusion or a foot-gun, I also agree with @nobu (Nobuyoshi Nakada) that this is in spirit with how Ruby operates, where anything is overridable. Struct
has been behaving in the exact same way for years:
irb(main):001:0> Foo = Struct.new(:hash)
=> Foo
irb(main):002:0> Foo.new(42).hash
=> 42
irb(main):003:0> Bar = Struct.new(:bar)
=> Bar
irb(main):004:0> Bar.new(42).hash
=> 4004416633903135689
Having said that, if the proposal was to add a warning for when users override some special methods, like hash
or object_id
or something, then I would be all for that. A warning for these situations is good enough to warn people who might be doing this by mistake, but is not as drastic as an error preventing them from doing it.