Create array and append key and value in each - ruby-on-rails

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]=[]}

Related

Updating Ruby Hash Values with Array Values

I've created the following hash keys with values parsed from PDF into array:
columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
h = Hash[columns.map.with_index.to_h]
=> {"Sen"=>0, "P-Hire#"=>1, "Emp#"=>2, "DOH"=>3, "Last"=>4, "First"=>5}
Now I want to update the value of each key with 6 equivalent values from another parsed data array:
rows = list.text.scan(/^.+/)
row = rows[0].tr(',', '')
#data = row.split
=> ["2", "6", "239", "05/05/67", "Harp", "Erin"]
I can iterate over #data in the view and it will list each of the 6 values. When I try to do the same in the controller it sets the same value to each key:
data.each do |e|
h.update(h){|key,v1| (e) }
end
=>
{"Sen"=>"Harper", "P-Hire#"=>"Harper", "Emp#"=>"Harper", "DOH"=>"Harper", "Last"=>"Harper", "First"=>"Harper"
So it's setting the value of each key to the last value of the looped array...
I would just do:
h.keys.zip(#data).to_h
If the only purpose of h is as an interim step getting to the result, you can dispense with it and do:
columns.zip(#data).to_h
There are several ways to solve this problem but a more direct and straight forward way would be:
columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
...
#data = row.split
h = Hash.new
columns.each_with_index do |column, index|
h[column] = #data[index]
end
Another way:
h.each do |key, index|
h[key] = #data[index]
end
Like I said, there are several ways of solving the issue and the best is always going to depend on what you're trying to achieve.

Ruby hash with string in Keys and an Array in Value

Hi i'am new in ruby and i want to get a Hash with string in keys and an Array in value, like this :
Hash = new HashMap
for (issue :is)
Hash.add(is.user_name)
if(hash.contains(is.user_name)) then
hash.value.add(is)
end
end
to get a result like this :
{"jane"[issue123,issue234,issue345]; "mike" [issue333,issue444,issue555]; "Alain" [issue876,issue987,issue356] }
jane have [issue123,issue234,issue345]
thanks
Something like below:
result = Hash.new { |hash, key| hash[key] = [] }
issues.each do |issue|
result[issue.user_name].push issue
end

Clear all values in nested ruby hash

How can I remove all values from ruby has. I don't want to remove keys just values.
For example:
here is my hash: {'a'=>{'b'=>'c'},'d'=>'e','f'=>{'g'=>''}}
I want this: {'a'=>{'b'=>nil},'d'=>nil,'f'=>{'g'=>nil}}
I don't want to delete the nested hashes. The nesting level varies from one to six levels
thanx
You can write custom delete_values! method, like this:
class Hash
def delete_values!
each_key do |key|
self[key].is_a?(Hash) ? self[key].delete_values! : self[key] = nil
end
end
end
{'a'=>{'b'=>'c'},'d'=>'e','f'=>{'g'=>''}}.delete_values!
# => {"a"=>{"b"=>nil}, "d"=>nil, "f"=>{"g"=>nil}}
h = {'a'=>{'b'=>'c'},'d'=>'e','f'=>{'g'=>''}}
def clean_hash h
h.each do |key, value|
if value.instance_of? Hash
clean_hash value
else
h[key] = nil
end
end
end
clean_hash h
#{"a"=>{"b"=>nil}, "d"=>nil, "f"=>{"g"=>nil}}
h = {'a'=>{'b'=>'c'},'d'=>'e','f'=>{'g'=>''}}
def cleaned_hash(h)
h.reduce({}) do |memo, (key, val)|
memo[key] = if val.is_a? Hash
cleaned_hash(val)
else
nil
end
memo
end
end
cleaned_hash h
# => {"a"=>{"b"=>nil}, "d"=>nil, "f"=>{"g"=>nil}}
This will not modify your hash but instead give you cleaned copy

Ruby convert all values in a hash to string

I have the following snippet of code to fetch certain columns from the db:
#data = Topic.select("id,name").where("id in (?)",#question.question_topic.split(",")).map(&:attributes)
In the resulting Array of Hashes which is :
Current:
#data = [ { "id" => 2, "name" => "Sports" }]
To be changed to:
#data = [ { "id" => "2", "name" => "Sports" }]
I want to convert "id" to string from fixnum. Id is integer in the db. What is the cleanest way to do this?
Note: After using .map(&:attributes) it is not an active record relation.
You can do it with proper map usage:
topics = Topic.select("id,name").where("id in (?)",#question.question_topic.split(","))
#data = topics.map do |topic|
{
'id' => topic.id.to_s,
'name' => topic.name
}
end
What you're looking for is simply
#data.each { |obj| obj["id"] = obj["id"].to_s }
There isn't really a simpler way (I think that's straightforward enough anyway).
Going by the title which implies a different question - converting every value in the hash to a string you can do this:
#data.each do |obj|
obj.map do |k, v|
{k => v.to_s}
end
end
Just leaving that there anyway.
You can use Ruby's #inject here:
#data.map do |datum|
new_datum = datum.inject({}) do |converted_datum, (key, value)|
converted_datum[key] = value.to_s
converted_datum
end
end
This will work to convert all values to strings, regardless of the key.
If you are using Rails it can be even cleaner with Rails' #each_with_object:
#data.map do |datum|
datum.each_with_object({}) do |(key, value), converted_datum|
converted_datum[key] = value.to_s
end
end
This will iterate all the key names in the hash and replace the value with the #to_s version of the datum associated with the key. nil's converted to empty strings. Also, this assumes you don't have complex data within the hash like embedded arrays or other hashes.
def hash_values_to_string(hash)
hash.keys.each {|k| hash[k]=hash[k].to_s}; hash
end

Ruby On Rails : create nested Array

I'm trying to make an array of objects, let's call it "categories", and I want each object in this array to have an array called "items" within it, so the result will be something like this:
[category:id=11, name="beer", items[1,2,3,4]]
I've tried this code:
#category ||= Array.new
#categoryItems ||= Array.new
#venues.categories.enabled.each do |category|
#category.push(category)
#categoryItems.push(category.items.enabled)
end
but I don't know how to name the items inside so I can use them in json afterward. How can I do this?
You can try create hash.
#category ||= Array.new
#venues.categories.enabled.each do |category|
hash = {}
hash[:category][:id] = category.id
hash[:category][:name] = category.name
hash[:category][:items] = category.items.enabled.pluck(:id).join(',')
#category << hash
end

Resources