From: "wardrop (Tom Wardrop)" Date: 2013-11-15T14:48:05+09:00 Subject: [ruby-core:58356] [ruby-trunk - Feature #9108] Hash sub-selections Issue #9108 has been updated by wardrop (Tom Wardrop). Enumerator includes Enumerable, as does Hash. Enumerator introduces a few new methods that revolve around the concept of a cursor, but otherwise everything else comes from Enumerable. My whole point is that for anyone using #reject or #select to retrieve an Enumerator from a Hash (which really no one should be doing), there's a good chance their code will still work, as long as they're not using the extra cursor functionality exclusive to Enumerators. Hash#select(*keys) is such an appropriate interface for obtaining a subset of a hash, as that's exactly what the #select and #reject methods are intended for. It would be silly in my opinion to introduce a new method. The question is, should Hash#select without arguments return a copy of the original hash, or an empty hash? Thinking about it, I'd say Hash#select should return an empty hash if no arguments are given, though this completely breaks compatibility for anyone using Hash#select (without arguments) as a means of obtaining an enumerator. Hash#reject without an argument should definitely return a full copy of the original hash. ---------------------------------------- Feature #9108: Hash sub-selections https://bugs.ruby-lang.org/issues/9108#change-42953 Author: wardrop (Tom Wardrop) Status: Open Priority: Normal Assignee: Category: Target version: =begin Hi, I seem to regularly have the requirement to work on a sub-set of key/value pairs within a hash. Ruby doesn't seem to provide a concise means of selecting a sub-set of keys from a hash. To give an example of what I mean, including how I currently achieve this: sounds = {dog: 'woof', cat: 'meow', mouse: 'squeak', horse: 'nay', cow: 'moo'} domestic_sounds = sounds.select { |k,v| [:dog, :cat].include? k } #=> {dog: 'woof', cat: 'meow'} I think a more concise and graceful solution to this would be to allow the Hash#[] method to take multiple arguments, returning a sub-hash, e.g. domestic_sounds = sounds[:dog, :cat] #=> {dog: 'woof', cat: 'meow'} I had a requirement in the current project I'm working on to concatenate two values in a hash. If this proposed feature existed, I could of just done this... sounds[:dog, :cat].values.join #=> 'woofmeow' You could do something similar for the setter also... sounds[:monkey, :bat] = 'screech' sounds #=> {dog: 'woof', cat: 'meow', mouse: 'squeak', horse: 'nay', cow: 'moo', monkey: 'screech', bat: 'screech'} Concise, convenient and readable. Thoughts? =end -- http://bugs.ruby-lang.org/