Merge arrays in Ruby/Rails
Like this?
⚡️ irb
2.2.2 :001 > [1,2,3] + [4,5,6]
=> [1, 2, 3, 4, 5, 6]
But you don't have 2 arrays.
You could do something like:
@movie = Movie.first()
@options = Movie.order("RANDOM()").first(3).to_a << @movie
How to merge two array objects in ruby?
array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
p array1 + array2
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}]
Or maybe this is superfluous:
array1 = [{ID:"1",name:"Dog"}]
array2 = [{ID:"2",name:"Cat"}]
array3 = [{ID:"3",name:"Duck"}]
p [array1, array2, array3].map(&:first)
# => [{:ID=>"1", :name=>"Dog"}, {:ID=>"2", :name=>"Cat"}, {:ID=>"3", :name=>"Duck"}]
Merge array at specific index in Ruby
You can use the normal element assignment, Array#[]=
and pass in the start
and length
parameters:
Element Assignment — Sets the element at index, or replaces a subarray from the start index for length elements, or replaces a subarray specified by the range of indices.
(emphasis mine) So, for instance:
@a1 = [0,0,0,0,0]
a2 = [1,1]
@a1[1, a2.length] = a2
@a1 # => [0, 1, 1, 0, 0]
@a1 = [0,0,0,0,0]
@a1[@a1.length - a2.length, a2.length] = a2
@a1 # => [0, 0, 0, 1, 1]
How to merge an array of arrays together into a single array?
[["convertible", "2010", "red"], ["convertible", "2010", "green"]].flatten!
Array of arrays merge in Rails
You could use Hash#merge! method with a block for that:
initial = [['Area1', 12345], ['Area2', 54321]].to_h
initial.merge!({'Area1' => 1212 }) { |_,v1,v2| [v1,v2].flatten }
#=> {"Area1"=>[12345, 1212], "Area2"=>54321}
and if you want the result to be an array, you can use
initial.merge!({'Area1' => 1212 }) { |_,v1,v2| [v1,v2].flatten }.to_a
Merge and interleave two arrays in Ruby
You can do that with:
a.zip(s).flatten.compact
Ruby - Merge two arrays and remove values that have duplicate
You can do the following!
# Merging
c = a + b
=> [1, 2, 3, 4, 5, 2, 4, 6]
# Removing the value of other array
# (a & b) is getting the common element from these two arrays
c - (a & b)
=> [1, 3, 5, 6]
Dmitri's comment is also same though I came up with my idea independently.
How to add and merge values from different array of hashes in ruby on rails
Using two helper methods for a DRY code and using Enumerable#sum, Enumerable#group_by, Hash#merge, Hash#transform_values and also other methods you can find in the documentation.
I'm using also Object#then here.
def sum_price_tax(ary)
ary.first.merge ary.then { |ary| { "Price" => ary.sum { |h| h["Price"].to_f }, "Tax" => ary.sum { |h| h["Tax"].to_f} } }
end
def group_and_sum(array_of_hash)
array_of_hash.group_by { |h| h["Date"] }.transform_values { |ary| sum_price_tax(ary) }
end
After the methods are defined, you can do:
a1 = group_and_sum(array_of_hash1)
a2 = group_and_sum(array_of_hash2)
a1.map { |k, v| v.merge(a2[k] || {}) { |h, old_val, new_val| old_val.is_a?(Float) ? old_val - new_val : old_val } }
#=> [{"Date"=>"2019-07-01", "Country"=>"US", "Email"=>"sample1@gmail.com", "Price"=>2.2121007000000006, "Tax"=>6.254, "Name"=>"John"}, {"Date"=>"2019-06-30", "Country"=>"US", "Email"=>"sample3@gmail.com", "Price"=>17.854323, "Tax"=>7.12343}, {"Date"=>"2019-07-02", "Country"=>"UK", "Email"=>"sample4@gmail.com", "Price"=>4.0019787, "Tax"=>1.9798780000000002, "Name"=>"Sam"}]
In this way also the "Name"
is present.
One way you could get rid of
"Name"
is using Object#tap and Hash#delete:a1.map { |k, v| v.merge(a2[k] || {}) { |h, old_val, new_val| old_val.is_a?(Float) ? old_val - new_val : old_val }.tap { |h| h.delete("Name") } }
#=> [{"Date"=>"2019-07-01", "Country"=>"US", "Email"=>"sample1@gmail.com", "Price"=>2.2121007000000006, "Tax"=>6.254}, {"Date"=>"2019-06-30", "Country"=>"US", "Email"=>"sample3@gmail.com", "Price"=>17.854323, "Tax"=>7.12343}, {"Date"=>"2019-07-02", "Country"=>"UK", "Email"=>"sample4@gmail.com", "Price"=>4.0019787, "Tax"=>1.9798780000000002}]
Related Topics
Ruby Split String by Repeating Characters or a Space
How to Establish a Ssl Enabled Tcp/Ip Connection in Ruby
How to Use Nokogiri::Xml::Reader to Parse Large Xml Files
Convert Array to Hash While Preserving Array Index Values in Ruby
How to Generate PDF from Markdown Using Pure Ruby
Detect Rspec Test Failure on After Each Method
Finding Lines in a Text File Matching a Regular Expression
Call Task More Than Once in Rails 3 Generator
Url_For of a Custom Restful Resource (Composite Key; Not Just Id)
Ruby Model Output Id as Object Oid
Error Installing a Pod - Bus Error at 0X00000001045B8000
Why Do You Need "Require 'Bundler/Setup'"
Rails 3 Validates Inclusion of When Using a Find (How to Proc or Lambda)
Watir. Scroll to a Certain Point of the Page
How to Save Dates in Local Timezone to Db with Rails3