properly access key and value to handle multiple records - ruby-on-rails

The following
#bucketitems = Bucketitem.group(:p_id).having('count("p_id") > 1').count(:p_id)
generates a hash of cases
{"00000450155"=>3, "00002860120"=>2, "00002870129"=>2, [...]}
If #bucketitems.first called, an array is given ["00000450155", 3]
How can each case now be invoked
#bucketitems.each do |key, value|
#items = Bucketitem.where('p_id = ?', "00000450155").to_a
so that the resulting array can be processed (complete missing data, delete duplicate records...)?
#items = Bucketitem.where('p_id = ?', key).to_a
is returning nil...

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

Create array and append key and value in each

I want to create a array and then to insert values for each key (key should be the value from each). But seems to not working. This is my code.
#options = %w(Services Resources)
#images = []
#options.each do |value|
#images[value] << Media::Image.where(type: "Media::#{value.singularize}Image")
end
#images is an array so referencing an element in it should be #images[Integer] and value is a string (in the first iteration it's "Services" and in the second "Resources"). Instead, what would work for you is Hash:
#options = %w(Services Resources)
#images = {}
#options.each do |value|
#images[value] = Media::Image.where(type: "Media::# {value.singularize}Image")
end
#images is a Array, Array can not use as a Hash.
Maybe you want create a Hash like this
#images = Hash.new {|h,k| h[k]=[]}

rails 4 data iteration from activerecord search

I am trying to iterate over a hash returned from an active record search.
the data comes back {[k, v] => v, [k,v] => v, etc.} and I need to place that data in 3 separate columns of a table.
what I have so far in a helper is
data = {}
connector = 0
us_cords = 0
eu_cords = 0
molex_connector = 0
chart_data_two.each do |key, value|
data[key[0]] ||= Hash.new
data[key[0]][key[1]] = value
end
return data
This gives me the k out of the k,v pair above and then a hash with "v" => v from above.
so I am having a hard time wrapping my head around iterating over the data hash and putting it into the view table in each column.
The view has #table_data_two = chart_qty_monthly_data(#chart_data_two) and then #table_data_two.each do |k,v| for generating each row/column.
Eventually it might be nice to do only one merged cell for month with 4 cells for model and then the quantities
Here's one way to build that:
data = Hash.new { |h, k| h[k] = {} }
chart_data_two.each do |key, value|
model_quantity = { key[0] => value }
data[key[1]].merge!(model_quantity)
end
If you want it to be in order by month, you can change the keys to integers and sort it:
data = Hash.new { |h, k| h[k] = {} }
chart_data_two.each do |key, value|
model_quantity = { key[0] => value }
data[key[1].to_i].merge!(model_quantity)
end
sorted_data = data.sort.to_h
It's not perfect, so I'll look it over again and see what could be improved, but it will at least get you started, assuming I understood your question correctly.
ended up doing it a bit different:
data = {}
#initialize hash keys in the order you want them to end up in
(1..12).each do |month|
data[month] = {"Connector" => 0, "US Cords" => 0, "EU Cords" => 0}
end
chart_data_two.each do |key, value|
#key[1] is month. we're referencing the keys we initialized above
#key[2] is model. we're adding a new key to the nested hash we initialized above
#logger.info "#{key[0]}, #{key[1]}, #{value}"
data[key[1].to_i][key[0]] = value
#logger.info "%%%%%%%% inside iterator #{data}"
end
#logger.info "$$$$$ passing #{data} into chart"
return data
end
I got help with figuring that out, but I wanted to post it here.

Split an Array of arrays into 2 separate arrays in Ruby

I have a hash with some key value pairs as below:
#level2 = #l2.inject(Hash.new(0)) { |hash,element|
hash[element] +=1
hash }
I perform some sorting on the hash based on the keys.
#level2 = #level2.sort_by { |x, _| x }.reverse
Now I assume that the sort_by gives me an Array of Arrays. I want to split this into 2 arrays such that my first array should contain all keys and second array should contain all values.
The hash#keys and hash#values are not accessible after sorting the hash. So that does not work in this case.
Regardless of how you make the hash it will will have a Hash#keys method and a Hash#values. They both return arrays that are just what you seem to want.
keys_array = #level2.keys
values_array = #level2.values
You could iterate over the array of arrays and add each element to a new array. This would keep the order of the elements.
keys_array = []
values_array = []
#level2.each do |key, value|
keys_array << key
values_array << value
end

Ruby on Rails 2 search string in Hash

I need help with this...
I have a hash like this:
#ingredients = Hash.new
#ingredients[1] = "Biscottes Mini(recondo)"
#ingredients[2] = "Abadejo"
#ingredients[3] = "Acelga"
#ingredients[4] = "Agua de Coco"
#ingredients[5] = "Ajo"
#ingredients[6] = "Almidón de Arroz"
#ingredients[7] = "Anillos Con Avena Integral cheerios (nestle)"
#ingredients[8] = "Apio"
I need to search into that hash in order to find "Biscottes Mini(recondo)" when I write "scotte"
Some help?
Thk!
Why do you use a Hash here and not an Array? You do not seem to use other keys than integers.
Anyway, this solution works for both Array and Hashes:
search_term = 'scotte'
# you could also use find_all instead of select
search_results = #ingredients.select { |key, val| val.include?(search_term) }
puts search_results.inspect
See http://ruby-doc.org/core/classes/Enumerable.html#M001488
You can call select (or find if you only want the first match) on a hash and then pass in a block that evaluates whether to include the key/value in the result hash. The block passes the key and value as arguments, so you can evaluate whether either the key or value matches.
search_value = "scotte"
#ingredients.select { |key, value| value.include? search_value }

Resources