1

I have the following array of arguments that has a hash with the args keys and their relevant passed values:

args_array = [{:collection=>["abe", "<mus>", "hest"], :include_blank=>true, :required=>true}]

I need to filter this hash to just get only some keys (like :include_blank and :required) in this example, with their relevant values like so:

filtered_args_hash = {:include_blank=>true, :required=>true}

So the collection arg is excluded, and just the include_blank, and required in which I specified are the ones returned.

Update:

Here is a keys array of symbols in which I need to filter according to them:

filter_keys = %i(include_blank required)

How I can do that?

1
  • Yes, keys = %i(include_blank required) Commented Jul 1, 2015 at 13:48

4 Answers 4

2

One way is to use Hash#keep_if:

args_array[0].dup.keep_if {|k| filter_keys.include? k}
# => {:include_blank=>true, :required=>true}

Note that .dup is here to prevent args_array from being modified, don't use it if you do want args_array to be updated.

Sign up to request clarification or add additional context in comments.

1 Comment

That modifies args_array[0] though. If I understand the question correctly, that behavior doesn't seem to be okay (maybe it is). Hash#select can be used in this case.
1

The following should do solve your problem:

 args_array.collect {|a| a if a[:include_blank] == true && a[:required=>true] == true }.compact

or

dup_list = args_array.dup
dup_list.delete_if {|a| !(a[:include_blank] == true && a[:required=>true] == true) }

2 Comments

But I need the include_blank and required returned with their values, whether they are true or false or whatever.
So you want to group them by include_blank and required ?
1
args_array.map do |elem| 
  elem.select do |k, _| 
    %i(include_blank required).include? k
  end
end

Comments

1

You tagged as Rails so you can use Hash#slice:

args_array[0].slice *filter_keys
# => {:include_blank=>true, :required=>true}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.