removing a value from hash if key matches rails - ruby-on-rails

I have seen many answers as removing any key which has value of nil or "", But this is not what i want.
I have a hash like this
{"firstname"=>"Jie",
"lastname"=>"Pton",
"email"=>"jami4#yahoo.com",
"country_id"=>"1",
"payment_method"=>"0",
"insight_id"=>"",
"password"=>""}
And I only want to remove the password attribute from hash if its empty, NOT ALL which are empty

More generic solution: for the hash given as an input (I assume it’s params, so let’s call it params) and the list of fields to be removed when empty:
TO_REMOVE_EMPTY = %w|password|
params.delete_if { |k, v| TO_REMOVE_EMPTY.include?(k) && v.empty? }

hash.delete('password') if hash['password'].blank?

You can also use this solution:
hash.reject { |k,v| v.nil? || v.empty? }

You can use:
hash.reject{|k,v| k == 'password' && (v.nil? || v.empty?)}
or if you want to remove "password" key from original hash you can use "!"
eg. hash.reject!{|k,v| k == 'password' && (v.nil? || v.empty?)}

Related

how to check if a certain key-value pair exists in array of hashes as json in ruby on rails

I have an array of hashes as json, so how to check my array of hashes contains a hash with a given key-value pair.
This is my json
[{"question"=>"0a2a3452", "answer"=>"bull"}, {"question"=>"58deacf9", "answer"=>"bullafolo"}, {"question"=>"32c53e5f", "answer"=>"curosit"}, {"question"=>"b5546bcf", "answer"=>""}, {"question"=>"0f0b314", "answer"=>""}]
I tried looping through the json array, but this is tedious, as I need to check that if that json has that hash with a given key-value pair
It's a questionnaire form, in which I have to perform an update on answers
if !#client_find.nil?
#client_find.questionnaire
params[:commit].each do |key, value|
#json=[]
#json = #client_find.questionnaire
if !value.empty? && #json.include?(key)
puts "blunderc "+ value.inspect
#new_append = Hash.new
#new_append[:question] = key
#new_append[:answer]= value
#json << #new_append
end
if !key.empty? && !value.empty?
#logic
#json.each do |u|
if (u.key? key)
puts "bothu "+ u[key].inspect
u[key] = value
end
end
end
end
Array#any? iterates through the array. In each iteration I check wether the current hash has the searched question key or not. If a hash is found Array#any? returns true otherwise false.
array = [{"question"=>"0a2a3452", "answer"=>"bull"}, {"question"=>"58deacf9", "answer"=>"bullafolo"}, {"question"=>"32c53e5f", "answer"=>"curosit"}, {"question"=>"b5546bcf", "answer"=>""}, {"question"=>"0f0b314", "answer"=>""}]
search_for_key = '0a2a3452'
array.any?{|hash| hash['question'] == search_for_key}
I'll assume that you want to check the existence of a hash which has the key/value pair "quesetion" => "some-value".
Here's how you can do it:
array.any? { |item| item['question'] == 'some-question-id' }
Considering your are checking for a particular key exists or not
#json.any? {|obj| obj.key?(your_particular_key)
You can filter the array using Enumerable#select to get only the hashes that contains the desired key.
filtered = my_hash.select { |item| item['desired_key'] }
That's possible because nil is falsey. If you input is a raw JSON you'll need to parse it to a Ruby hash using JSON#parse or any other equivalent method.
filtered will give you all the hashes that contain the desired_key.
Is that what you want ?
Btw guitarman's answer is way better !
questions = [{"question"=>"0a2a3452", "answer"=>"bull"}, {"question"=>"58deacf9", "answer"=>"bullafolo"}, {"question"=>"32c53e5f", "answer"=>"curosit"}, {"question"=>"b5546bcf", "answer"=>""}, {"question"=>"0f0b314", "answer"=>""}]
result = questions.find { |question| question['question'] == "Bonour" }
if result.nil?
puts "Not found"
else
puts "#{result['question']} #{result['answer']}"
end

ruby regex to find nil or blank values for import csv?

row = {"joining_date"=>"18/07/2015", "name"=>" Joe Doe ", "company"=>" Google", "location"=>" New York ", "role"=>"developer", "email"=>"joe#doe.com", "mobile"=>"11-(640)123-45674", "address"=>"4 XYZ Road", "validity"=>"true"}
row is invalid only if any one of the fields(joining_date, name, company, location, email, address) is nil or not present.
def is_valid?
valid = true
if row[:name] == nil || row[:joining_date] == nil || row[:address] == nil || row[:email] == nil || row[:company] == nil || row[:location] == nil
valid = false
end
valid
end
Is there any way that I can simplify and refactor the above method in rails to find it more efficient using regex?
Probably, but I wouldn't use a regex as it's in a hash. As you're using rails you can use present? or blank?.
row.values.any?(&:blank?)
Would return true if any are blank
for your case
def is valid?
row.values.all?(&:present?)
end

How to accept hash parameters

Here are the parameters being passed:
{"utf8"=>"✓",
"authenticity_token"=>"j3R0aro/Arg4Y3Zu6zIIxZYbYTxqoqyKEGc11CkvYDU=",
"inventory"=>{
"9"=>"0",
"12"=>"0",
"1"=>"0",
"2"=>"0",
"3"=>"0",
"10"=>"0",
"11"=>"0",
...
}
}
I can't seem to grab the params in inventory, for whatever reason, the code below keeps wanting to grab the inventory as one long array of hashes rather than the hashes themselves. What am I doing wrong?
def inventory_params
params.permit(inventory: [{:itemlist_id => :quantity}] )
#inventory_params = params.reject { |k, v| (v == "") || ( v == "0" ) }
end
I also tried params.permit(inventory: {:itemlist_id => :quantity} ) which didn't work either
params.require(:model_name).permit(:inventory)
will work I guess.
What ended up working:
params["inventory"]

Rails strong parameters of enumerated type

I've got paramerers which are sent by a form like:
{ "mac"=>{"0"=>["111", "222"], "1"=>["333", "444"]} }
How can I permit them in a proper way, because I've found just an ugly solution:
params.permit(mac: Hash[(0..100).map { |i| [i.to_s, []] }])
Fetch the keys out of the :mac key and then permit them.
mac_keys = params.fetch(:mac, {}).keys
params.permit(mac: mac_keys)
will you consider the hash's keep_if method, as params is just a hash.
params[:mac].keep_if {|k, v| k.to_i >= 0 and k.to_i <= 100}

Hashes in hashes ruby on rails

I'm passing the below information through parameter from view to controller
parameters:{"Something"=>{"a" => "1", "b" => "0", "c" => "1", "d" => "0" #and so on}}
I want to access all the characters that have "1" as their value and concatenate into the string.
I tried
Something.each do |key, value|
if(value == "1")
string = string + key
end
end
It is throwing error saying that it could not execute nil.each and that i might be expecting an array.
It appears to me that Something is a hash and in turn has some hashes in it.
So i initialised Something to
Something = Hash.new { |Something, k| Something[k] = Hash.new }
But i still get the same error.
Just work with the params hash. This should do what you need:
params["Something"].select {|k, v| v == "1"}.keys.reduce(:+)
select filters the params to only those with the value "1"
keys returns an array with all the keys in the hash
reduce joins all elements with a concat operation (+)
Edit
To concatenate and add the "Extra" word:
For each parameter:
params["Something"].select {|k, v| v == "1"}.keys.inject("") {|result, p| result += "Extra #{p}"}
Only to the extra parameters, but not to the first one:
params["Something"].select {|k, v| v == "1"}.keys.inject {|result, p| result += "Extra #{p}"}
See more information on inject here.

Resources