Mapping values from two array in Ruby
@Michiel de Mare
Your Ruby 1.9 example can be shortened a bit further:
weights.zip(data).map(:*).reduce(:+)
Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use:
weights.zip(data).map(&:*).reduce(&:+)
How to loop over two arrays and create a map in Ruby
If what you need is an array of hashes, where every hash has the keys shape
and color
, then you can use product
between array1 and array2 and then just map the result of that:
array1.product(array2).map { |shape, color| { shape: shape, color: color } }
# [{:shape=>"square", :color=>"red"}, {:shape=>"square", :color=>"blue"}, {:shape=>"circle", :color=>"red"}, {:shape=>"circle", :color=>"blue"}, {:shape=>"triagle", :color=>"red"}, {:shape=>"triagle", :color=>"blue"}]
ruby map a function over multiple arrays
Use zip to combine each element with its corresponding in two element array and than map
asc.zip(dsc).map { |a, b| a * b }
=> [0, 4, 6, 6, 4, 0]
How can I map values in two different arrays as properties on an equivalent array of objects?
a.zip(b).map { |args| Obj.new(*args) }
Per your edit:
a.zip(b).map { |(a, b)| Obj.new(a, b) }
Ruby join two arrays by key value
This is a way to do it.
sounds = arr2[0]
results = arr1.map do |animal|
"#{animal["n"]}: #{sounds[animal["id"]]}"
end
puts results
# => cat: meow
# => dog: woof
Seems like the second array should just be a hash instead. There's no point creating an array if there's only one element in it and that number won't change.
pointless one-liner (don't use this)
puts arr1.map { |x| "#{x["n"]}: #{arr2[0][x["id"]]}" }
Combine two arrays in Ruby?
I would transform the two arrays to lookup hashes. Then collect all the ids to iterate. Map the ids into the foo
and bar
values, then zip them together.
foo_lookup = foo.to_h { |id| [id, {id: id}] } # change `{id: id}` into `id` for the other output
bar_lookup = bar.to_h { |item| [item[:id], item] }
ids = foo_lookup.keys | bar_lookup.keys
res = ids.map(&foo_lookup).zip(ids.map(&bar_lookup))
#=> [[{:id=>1}, nil], [{:id=>2}, {:id=>2}], [nil, {:id=>4}]]
Returning Multiple Values From Map
Use Enumerable#flat_map
b = [0, 3, 6]
a = b.flat_map { |x| [x, x+1, x+2] }
a # => [0, 1, 2, 3, 4, 5, 6, 7, 8]
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: Serializing Objects in a Database
Using a Ruby Script to Login to a Website via Https
What Is the Send() Method Used For
Array.Include? Multiple Values
Rails How to Switch Between Dev and Production Mode
What Are the Main Differences Between Sinatra and Ramaze
Creating an Empty File in Ruby: "Touch" Equivalent
"Ago" Date/Time Functions in Ruby/Rails
Which Ruby Memoize Pattern Does Activesupport::Memoizable Refer To
How to Check from Ruby Whether a Process with a Certain Pid Is Running
How to Sort a Hash by Value in Descending Order and Output a Hash in Ruby
Cleanest Way to Create a Hash from an Array
Cool Tricks and Expressive Snippets with Ruby Collections/Enumerables