From: "nobu (Nobuyoshi Nakada)" <nobu@...> Date: 2013-11-14T13:44:14+09:00 Subject: [ruby-core:58330] [ruby-trunk - Feature #9108] Hash sub-selections Issue #9108 has been updated by nobu (Nobuyoshi Nakada). wardrop (Tom Wardrop) wrote: > 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'} As `sounds[:dog]` returns 'woof', it should return the values only, even if it were introduced. > 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' Try: sounds.values_at(:dog, :cat).join('') > 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'} It feels ambiguous, since it looks like a kind of mulitple assignment to me. Rather it should be: sounds[:monkey, :bat] = 'screech' # sounds[:monkey] == 'screech' # sounds[:bat] == nil sounds[:cock, :hen] = 'cock-a-doodle-doo', 'cluck' # sounds[:cock] == 'cock-a-doodle-doo' # sounds[:hen] == 'cluck' shouldn't it? ---------------------------------------- Feature #9108: Hash sub-selections https://bugs.ruby-lang.org/issues/9108#change-42924 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/