rubyruby-hash

Fetching all keys and values from a hash at once in Ruby


In **Ruby, I want to fetch all keys and values at once without needing to iterate through the hash.

The keys are variables and the values of data type boolean.

In the new Example, the only parameters, which are exchangeable, are var1 => true and var2 => true. So, I want that the hash keys are treated as keywords.

New Example:

var1 = "Attr1"
var2 = "Attr2"
var3 = "Attr2"

hash = {var1 => true, var2 => true}

def method(h = {})

    puts("Works")

end


method(hash, var3 => true) #Error

Old Example:

hash = {var1 => true, var2 => false}
self.some_method_i_cant_change_1(var1 => true, var2 => false, var3 => true)
self.some_method_i_cant_change_2(var1 => true, var2 => false, var3 => true)
... n methods
self.some_method_i_cant_change_n(var1 => true, var2 => false, var3 => true)

It's not possible to pass the hash to that method directly.

So, self.some_method_i_cant_change(hash, var3 => true) isn't allowed


Solution

  • It is hard to understand the issue, but as I understand you need to call some method and pass single argument as hash using few existing hashes

    var1 = "Attr1"
    var2 = "Attr2"
    var3 = "Attr3"
    
    hsh = { var1 => true, var2 => true }
    
    def some_method(hsh = {})
      p hsh
    end
    
    # With hashes merge
    some_method(hsh.merge(var3 => true))
    
    # Using double splat
    some_method(var3 => true, **hsh)
    
    # With mutation of original hash
    hsh[var3] = true
    some_method(hsh)