From: dementiev.vm@... Date: 2020-03-04T23:42:30+00:00 Subject: [ruby-core:97361] [Ruby master Bug#16660] Struct#deconstruct_keys inconsistent behavior Issue #16660 has been updated by palkan (Vladimir Dementyev). (For some reason cannot edit the original post). > Prior to that change an empty hash was returned in both cases. I think, the less confusing behavior would be to ignore the unknown keys without "failing fast" (i.e., returning an empty Hash if key is unknown). That is: ```ruby s.deconstruct_keys([:a, :c]) #=> {a: 1} s.deconstruct_keys([:a, :b, :c]) #=> {a: 1, b: 2} ``` IMO, that better reflects the pattern matching: if some key is present in one pattern (one key set), it must be present in another pattern with the same key. I guess, that have been done for optimization (fail-fast if more keys then we have) but I believe that such optimization should be done within the pattern matching implementation, not a particular class API. The proposed behaviour would be even easier to optimize (e.g., we can re-use the deconstruction hash for keys subsets or cache the result of the key presence check). ---------------------------------------- Bug #16660: Struct#deconstruct_keys inconsistent behavior https://bugs.ruby-lang.org/issues/16660#change-84488 * Author: palkan (Vladimir Dementyev) * Status: Open * Priority: Normal * ruby -v: ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux] * Backport: 2.5: UNKNOWN, 2.6: UNKNOWN, 2.7: UNKNOWN ---------------------------------------- Here is an example of a kind of surprising (at least to me) `Struct#deconstruct_keys` behaviour: ```ruby klass = Struct.new(:a, :b) s = klass.new(1, 2) ``` 1) When some keys are not recognized and the total number of the keys is not greater than the size of the struct: ```ruby s.deconstruct_keys([:a, :c]) #=> {a: 1} ``` 2) When some keys are not recognized but the total number of the keys is greater than the size of the struct: ```ruby s.deconstruct_keys([:a, :b, :c]) #=> {} ``` It's not clear why the first one filters unknown keys and the latter one returns an empty Hash instead of the `{a: 1}`. This behaviour was introduced in https://github.com/ruby/ruby/commit/2439948bcc0ec9daf91cf79301195e59bad49aff. Prior to that change an empty hash was returned in both cases. -- https://bugs.ruby-lang.org/ Unsubscribe: