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.
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
Merge and interleave two arrays in Ruby
You can do that with:
a.zip(s).flatten.compact
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 2 arrays into same index value
Use zip
and join
:
array_1.zip(array_2).map { |a| a.join(' ') }
How to merge two arrays of hashes
uniq
would work if you concatenate the arrays in reverse order:
(b + a).uniq { |h| h[:key] }
#=> [
# {:key=>1, :value=>"bar"},
# {:key=>1000, :value=>"something"},
# {:key=>2, :value=>"baz"}
# ]
It doesn't however preserve the order.
What is the best way to merge two arrays (element + element), if elements itself are arrays
[Array1, Array2].transpose.map(&:flatten)
=> [[1, 2, 1, 4], [8, 11], [2, 3, 3, 6]]
RubyGuides: "Turn Rows Into Columns With The Ruby Transpose Method"
Each step explained:
[Array1, Array2]
=> [[[1, 2], [], [2, 3]],
[[1, 4], [8, 11], [3, 6]]]
Create a grid like array.
[Array1, Array2].transpose
=> [[[1, 2], [1, 4]], [[], [8, 11]], [[2, 3], [3, 6]]]
transpose switches rows and columns (close to what we want)
[Array1, Array2].transpose.map(&:flatten)
=> [[1, 2, 1, 4], [8, 11], [2, 3, 3, 6]]
flatten gets rid of the unnecessary nested arrays (here combined with map to access nested arrays)
Related Topics
Rails Generate Has_Many Association
Activerecord Objects in Hashes Aren't Garbage Collected -- a Bug or a Sort of Caching Feature
Find Records with Datetime That Match Today's Date - Ruby on Rails
What Alternatives to Irb Are There
What Are the Ruby's Object#Taint and Object#Trust Methods
Array Attribute for Ruby Model
Ruby: Explicit Scoping on a Class Definition
Ruby on Rails: What Reporting And/Or Charting Tools Are Available
How to Open Files Relative to Home Directory
Ruby Strftime: Month Without Leading Zero
How to Do Standard Deviation in Ruby
Respond_To' VS. 'Respond_To_Missing'
How to Get the Width of Terminal Window in Ruby
Can't Use Compass After Installing It
Heroku Gem Not Working with Rvm
Installing Ruby 2.3.X on Ubuntu 18.04 Is Causing an Error by the End of the Installation Process