0

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

6
  • there is a double splat, so hash keys are treated as keywords: self.some_method_i_cant_change(**hash) Commented Aug 3, 2023 at 16:21
  • foo(var1 => true, var2 => false) is equivalent to foo({var1 => true, var2 => false}) or foo(hash) with hash = {var1 => true, var2 => false}. Can you double check how the method is called? Commented Aug 3, 2023 at 18:41
  • @Stefan If there are predefined values, it doesn't work. I will edit my post to make it more clear. Example: a={"h" =>1, "b" => 2} def method(option={}) method("z"=>1,a) results in an error. And method("z"=>1,**a) does work Commented Aug 3, 2023 at 19:47
  • 4
    Maybe I'm being dense, but I don't understand your question and could really use a minimal reproducible example. I don't understand how the some_method_i_cant_change_* methods are intended to use their arguments. Commented Aug 3, 2023 at 22:21
  • Can you show the method signatures? How are they defined and what arguments do they take? Commented Aug 4, 2023 at 6:40

2 Answers 2

0

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Can you do something like this:

hash = {var1 => true, var2 => false}
self.some_method_i_cant_change(*(hash.map { |k, v| {k =>  v} }))

1 Comment

Thank you for answering my question. Unfortunately, i need to handle several methods, so I guess it's a good solution for one method but not for several methods. I will edit my post to be more clear, thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.