Method to invert a mapping along a given range - ruby

Say I have this collection of objects:
[
{value: 1, contents: "one"},
{value: 2, contents: "two"},
{value: 3, contents: "three"},
{value: 4, contents: "four"},
{value: 5, contents: "five"}
]
And want to invert the relation of values to contents, like so:
[
{value: 5, contents: "one"},
{value: 4, contents: "two"},
{value: 3, contents: "three"},
{value: 2, contents: "four"},
{value: 1, contents: "five"}
]
I was unable to think of an algorithm to accomplish this. I'm using Ruby, but I'm not so concerned about the code as I am about the method of accomplishing this.

a = [
{value: 1, contents: "one"},
{value: 2, contents: "two"},
{value: 3, contents: "three"},
{value: 4, contents: "four"},
{value: 5, contents: "five"}
]
a.map{|h| h[:value]}.reverse.zip(a.map{|h| h[:contents]})
.map{|k, v| {value: k, contents: v}}
# =>
# [
# {:value=>5, :contents=>"one"},
# {:value=>4, :contents=>"two"},
# {:value=>3, :contents=>"three"},
# {:value=>2, :contents=>"four"},
# {:value=>1, :contents=>"five"}
#]
Or,
a.each_index.map{|i| {value: a[-i - 1][:value], contents: a[i][:contents]}}

Letting arr equal your array of hashes, here are a couple of ways you could do it.
Two passes, no indices
value_vals = arr.map {|h| h[:value]}.reverse
#=> [5, 4, 3, 2, 1]
arr.map { |h| {value: value_vals.shift, contents: h[:contents]}}
#=> [{:value=>5, :contents=>"one"},
# {:value=>4, :contents=>"two"},
# {:value=>3, :contents=>"three"},
# {:value=>2, :contents=>"four"},
# {:value=>1, :contents=>"five"}]
One pass, but not pretty
arr.each_index.map {|i,a| {value: arr[-1-i][:value], contents: arr[i][:contents]}}
#=> [{:value=>5, :contents=>"one"},
# {:value=>4, :contents=>"two"},
# {:value=>3, :contents=>"three"},
# {:value=>2, :contents=>"four"},
# {:value=>1, :contents=>"five"}]

TL;DR
arr.zip(arr.reverse).map {|a, b| a.merge(value: b[:value]) }
Since reverse makes a copy of the array, this will take twice as much memory as other methods—which for most data sets probably isn't an issue at all. But if it is, there's an easy way to avoid it. See the "Bonus" section at the end of my answer.
Building an algorithm
The simplest (and probably best) solution is to walk the array, and for each item get the :value from its counterpart at the other end of the array. You can get an item's "counterpart" by subtracting the item's index from the index of the last item (i.e. the size of the array minus 1). So, if you have five items in an array called arr, the steps of the algorithm looks like this:
end_idx = arr.size - 1 # => 4
new_arr = []
new_arr[0] = { value: arr[end_idx - 0][:value], contents: arr[0][:contents] }
new_arr[1] = { value: arr[end_idx - 1][:value], contents: arr[1][:contents] }
new_arr[2] = { value: arr[end_idx - 2][:value], contents: arr[2][:contents] }
new_arr[3] = { value: arr[end_idx - 3][:value], contents: arr[3][:contents] }
new_arr[4] = { value: arr[end_idx - 4][:value], contents: arr[4][:contents] }
As you can see, every step is the same but with one number incremented, so I bet you already know how to turn this into a loop:
end_idx = arr.size - 1 # => 4
new_arr = []
0.upto(end_idx) do |idx|
new_arr[idx] = { value: arr[end_idx - idx][:value],
contents: arr[idx][:contents] }
end
Easy, and to be honest a perfectly good solution. However, it's not very "Rubyish." How do we make it more Rubyish? I'm glad you asked!
Make it more Rubyish
It's a pretty common situation to want, as an output, an array with one item corresponding to each item in an input array. Because it's so common, we have the Enumerable#map method, which does exactly that: It "maps" every item in an input array (or other Enumerable) to an item in an output array.
map walks over the items of the array, which is just what we need, but it's missing one thing we need: The index of the current item. To get that, we can "chain" the with_index method onto the map method, and now, in addition to the array item itself, the block will be passed a second argument, which is its index. Now we have everything we need:
end_idx = vals.size - 1
arr.map.with_index do |hsh, idx|
{ value: arr[end_idx - idx][:value],
contents: hsh[:contents] }
end
Alternatively, if we don't want to explicitly specify the structure of the hash (as we might if the hash comes from, say, user input or a database query and might have keys other than :value and :contents that we want to preserve without having to keep track of changes to the input form or database schema), we could do this:
end_idx = vals.size - 1
arr.map.with_index do |hsh, idx|
hsh.merge(value: arr[end_idx - idx][:value])
end
But I've saved the best for last.
At last...
arr.zip(arr.reverse_each).map do |a, b|
a.merge(value: b[:value])
end
What's going on here? The Array#zip method takes two arrays and "zips" them up, so e.g. [1, 2, 3].zip([:a, :b, :c]) yields [[1, :a], [2, :b], [3, :c]], so we do that with our array and its reverse (or, rather, an Enumerable that yields successive items from the end of the array, which is what reverse_each returns), and then we use map to set the value at :value from the latter on a copy of the former (using merge).
Bonus: Why reverse_each and not just reverse? Because we can make it lazy! Suppose arr has a billion items. If you call arr.zip(arr.reverse), now you have a (two-dimensional) array with two billion items. Maybe that's not a big deal (or maybe you don't have anywhere near a billion items), but if it is, laziness can help us out:
new_enum = arr.lazy.zip(arr.reverse_each).map do |a, b|
a.merge(value: b[:value])
end
# => #<Enumerator::Lazy: ...>
All we've done is added lazy, and now we get an Enumerator back instead of an array. This won't even do any work until we call, say, each or some other Enumerable method on it, and when we do that it will only operate on as many items as we ask it to. For example, say we just want the first three items:
new_enum.take(3).to_a
# => [ { value: 1000000000, contents: "one" },
# { value: 999999999, contents: "two" },
# { value: 999999998, contents: "three" } ]
Thanks to laziness, we never had to make a copy of the whole array and reverse it (and take up the corresponding amount of memory); we only had to deal with three items.
And if you do want all of the items, but still want to avoid making a copy of the whole array, just call new_enum.to_a.

Related

Understanding Ruby sort_by

I am new to ruby and I struggle understanding sort_by!. This method does something magically I really don't understand.
Here is a simple example:
pc= ["Z6","Z5","Z4"]
c = [
{
id: "Z4",
name: "zlah1"
},
{
id: "Z5",
name: "blah2"
},
{
id: "Z6",
name: "clah3"
}
]
c.sort_by! do |c|
pc.index c[:id]
end
This procedure returns:
=> [{:id=>"Z6", :name=>"clah3"}, {:id=>"Z5", :name=>"blah2"}, {:id=>"Z4", :name=>"zlah1"}]
It somehow reverses the array order. How does it do that? pc.index c[:id] just returns a number. What does this method do under the hood? The documentation is not very beginners friendly.
Suppose we are given the following:
order = ['Z6', 'Z5', 'Z4']
array = [{id: 'Z4', name: 'zlah1'},
{id: 'Z5', name: 'blah2'},
{id: 'Z6', name: 'clah3'},
{id: 'Z5', name: 'dlah4'}]
Notice that I added a 4th hash ({id: 'Z5', name: 'dlah4'}) to the array array given in the question. I did this so that two elements of array would the same value for the key :id ("Z5").
Now let's consider how Ruby might implement the following:
array.sort_by { |hash| order.index(hash[:id]) }
#=> [{:id=>"Z6", :naCme=>"clah3"},
# {:id=>"Z5", :name=>"blah2"},
# {:id=>"Z5", :name=>"dlah4"},
# {:id=>"Z4", :name=>"zlah1"}]
That could be done in four steps.
Step 1: Create a hash that maps the values of the sort criterion to the values of sort_by's receiver
sort_map = array.each_with_object(Hash.new { |h,k| h[k] = [] }) do |hash,h|
h[order.index(hash[:id])] << hash
end
#=> {2=>[{:id=>"Z4", :name=>"zlah1"}],
# 1=>[{:id=>"Z5", :name=>"blah2"}, {:id=>"Z5", :name=>"dlah4"}],
# 0=>[{:id=>"Z6", :name=>"clah3"}]}
h = Hash.new { |h,k| h[k] = [] } creates an empty hash with a default proc that operates as follows when evaluating:
h[k] << hash
If h has a key k this operation is performed as usual. If, however, h does not have a key k the proc is called, causing the operation h[k] = [] to be performed, after which h[k] << hash is executed as normal.
The values in this hash must be arrays, rather than individual elements of array, due the possibility that, as here, two elements of sort_by's receiver map to the same key. Note that this operation has nothing to do with the particular mapping of the elements of sort_by's receiver to the sort criterion.
Step 2: Sort the keys of sort_map
keys = sort_map.keys
#=> [2, 1, 0]
sorted_keys = keys.sort
#=> [0, 1, 2]
Step 3: Map sorted_keys to the values of sort_map
sort_map_values = sorted_keys.map { |k| sort_map[k] }
#=> [[{:id=>"Z6", :name=>"clah3"}],
# [{:id=>"Z5", :name=>"blah2"}, {:id=>"Z5", :name=>"dlah4"}],
# [{:id=>"Z4", :name=>"zlah1"}]]
Step 4: Flatten sort_map_values
sort_map_values.flatten
#=> [{:id=>"Z6", :name=>"clah3"},
# {:id=>"Z5", :name=>"blah2"},
# {:id=>"Z5", :name=>"dlah4"},
# {:id=>"Z4", :name=>"zlah1"}]
One of the advantages of using sort_by rather than sort (with a block) is that the sort criterion (here order.index(hash[:id])) is computed only once for each element of sort_by's receiver, whereas sort would recompute these values for each pairwise comparison in its block. The time savings can be considerable if this operation is computationally expensive.
order = ['Z6', 'Z5', 'Z4']
array = [{id: 'Z4', name: 'zlah1'},
{id: 'Z5', name: 'blah2'},
{id: 'Z6', name: 'clah3'}]
array.sort_by { |hash| order.index(hash[:id]) }
#=> [{:id=>"Z6", :name=>"clah3"}, {:id=>"Z5", :name=>"blah2"}, {:id=>"Z4", :name=>"zlah1"}]
This doesn't magically reverse the order of the array. To explain what happens we first need to understand what order.index(hash[:id]) does. This becomes better visible with the map method.
array.map { |hash| order.index(hash[:id]) }
#=> [2, 1, 0]
Like you can see, the first element with id 'Z4' will return the number 2 since 'Z4' in the order array has index 2. The same happens with all other array elements. The retuned value is used to sort the objects, sort_by will always sort asynchronous, so the order of the above array should become [0, 1, 2]. However, the actual content is not replaced, the number is only used for comparison vs other elements. Thus resulting in:
#=> [{:id=>"Z6", :name=>"clah3"}, {:id=>"Z5", :name=>"blah2"}, {:id=>"Z4", :name=>"zlah1"}]

Translate Ruby hash (key,value) to separate keys

I have a map function in ruby which returns an array of arrays with two values in each, which I want to have in a different format.
What I want to have:
"countries": [
{
"country": "Canada",
"count": 12
},
{and so on... }
]
But map obviously returns my values as array:
"countries": [
[
"Canada",
2
],
[
"Chile",
1
],
[
"China",
1
]
]
When using Array::to_h I am also able to bringt it closer to the format I actually want to have.
"countries": {
"Canada": 2,
"Chile": 1,
"China": 1,
}
I have tried reduce/inject, each_with_object but in both cases I do not understand how to access the incoming parameters. While searching here you find many many similar problems. But haven't found a way to adapt those to my case.
Hope you can help to find a short and elegant solution.
You are given two arrays:
countries= [['Canada', 2], ['Chile', 1], ['China', 1]]
keys = [:country, :count]
You could write
[keys].product(countries).map { |arr| arr.transpose.to_h }
#=> [{:country=>"Canada", :count=>2},
# {:country=>"Chile", :count=>1},
# {:country=>"China", :count=>1}]
or simply
countries.map { |country, cnt| { country: country, count: cnt } }
#=> [{:country=>"Canada", :count=>2},
# {:country=>"Chile", :count=>1},
# {:country=>"China", :count=>1}]
but the first has the advantage that no code need be changed in the names of the keys change. In fact, there would be no need to change the code if the arrays countries and keys both changed, provided countries[i].size == keys.size for all i = 0..countries.size-1. (See the example at the end.)
The initial step for the first calculation is as follows.
a = [keys].product(countries)
#=> [[[:country, :count], ["Canada", 2]],
# [[:country, :count], ["Chile", 1]],
# [[:country, :count], ["China", 1]]]
See Array#product. We now have
a.map { |arr| arr.transpose.to_h }
map passes the first element of a to the block and sets the block variable arr to that value:
arr = a.first
#=> [[:country, :count], ["Canada", 2]]
The block calculation is then performed:
b = arr.transpose
#=> [[:country, "Canada"], [:count, 2]]
b.to_h
#=> {:country=>"Canada", :count=>2}
So we see that a[0] (arr) is mapped to {:country=>"Canada", :count=>2}. The next two elements of a are then passed to the block and similar calculations are made, after which map returns the desired array of three hashes. See Array#transpose and Array#to_h.
Here is a second example using the same code.
countries= [['Canada', 2, 9.09], ['Chile', 1, 0.74],
['China', 1, 9.33], ['France', 1, 0.55]]
keys = [:country, :count, :area]
[keys].product(countries).map { |arr| arr.transpose.to_h }
#=> [{:country=>"Canada", :count=>2, :area=>9.09},
# {:country=>"Chile", :count=>1, :area=>0.74},
# {:country=>"China", :count=>1, :area=>9.33},
# {:country=>"France", :count=>1, :area=>0.55}]
Just out of curiosity:
countries = [['Canada', 2], ['Chile', 1], ['China', 1]]
countries.map(&%i[country count].method(:zip)).map(&:to_h)
#⇒ [{:country=>"Canada", :count=>2},
# {:country=>"Chile", :count=>1},
# {:country=>"China", :count=>1}]

How to access two elements within nested hashes within an array?

I have the following array with nested hashes:
pizza = [
{ flavor: "cheese", extras: { topping1: 1, topping2: 2, topping3: 3} },
{ flavor: "buffalo chicken", extras: { topping1: 1, topping2: 2, topping3: 3} } } ]
If want to verify that I can get an order of "buffalo chicken" pizza with two toppings. I use the .map method to iterate through the array of hashes to verify that the "flavor" I want and the "extras" I want ( 2 toppings) are available. Bingo! The code I use works, returns true, and indeed these two elements are available. BUT, if I want to check if the "buffalo chicken" flavor is available and 5 toppings are also available, then it should return false, but instead, I get an Error message that says:
Failure Error: expect(Party).not_to be_available(pizza, "buffalo chicken", :toppings5) to return false, got []
Here is my code:
def self.available?(pizza, flavor, extra)
pizza.map { |x| x if x[:flavor] == flavor && x[:extra] == extra }
end
I'm trying to figure out why I get [] returned rather than false. Perhaps there is something I'm not understanding with the way .map is being used to iterate through my array of hashes? Without changing the structure of my array of hashes, could someone please help me understand?
You have several problems here:
The keys in the hash must be unique, so the two first toppings keys are ignored. Here is an example of a wrong hash { key: 1, key: 2, key: 3 } it becomes { key: 3 }.
You must not use hash as the name of a variable in any case, it's a method.
To find an element in an array of hashes, you can use the find method, e.g.:
>> h = [{ f: "cheese", extras: [1,2,3] }, { f: "buffalo", extras: [1,3] }]
>> h.find { |h| h[:f] == "cheese" && h[:extras].size > 2 }
=> {:f=>"cheese", :extras=>[1, 2, 3]}
There are a lot of methods to iterate over an array or hash. Read more about Enumerable module. Also don't be lazy and check documentation.

Apply something to certain value of a hash, return the whole hash

What is the proper way of doing so in Ruby in a functional and immutable way:
a = { price: 100, foo: :bar, bar: :baz }
def reduced_price(row)
row.merge(price: row[:price] / 2)
end
reduced_price(a) # => { price: 50, foo: :bar, bar: :baz }
I don't want to mutate anything and I don't like the consctruction row.merge(key: row[:key]) because it repeats the :key and refers to row twice. If there would be something like:
{a: 1, b: 2}.apply_to_key(:a) { |x| x * 10 } # => {a: 10, b: 2}
it would be great.
To sum up, I want a method that, when given a key, updates a single value of a hash by that key using the previous value, and then returns the whole hash.
And while I was writing the question, I have found the answer. Since SO suggests sharing my knowledge Q&A-style, here it is:
{a: 1, b: 2}.merge(a: nil) { |_, v| v * 10 } # => {a: 10, b: 2}
When you pass a block to hash.merge(other_hash), it will be executed for each pair of other_hash with parameters key, oldval, newval and should return resulting value. In a case above, my other_hash contains only one key I wanted to alter, and from the three params I care only for the second, old_val, to use it in my block.
It's perfectly chainable and doesn't mutate a thing. It has a bit of redundancy (having to pass nil or any other value to other_hash, having to ignore first parameter of the block), but I guess it's the closest I could get.
If you can suggest better answer, I will consider accepting it.

What is the best way to convert an array to a hash in Ruby

In Ruby, given an array in one of the following forms...
[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]
...what is the best way to convert this into a hash in the form of...
{apple => 1, banana => 2}
Simply use Hash[*array_variable.flatten]
For example:
a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"
a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"
Using Array#flatten(1) limits the recursion so Array keys and values work as expected.
NOTE: For a concise and efficient solution, please see Marc-André Lafortune's answer below.
This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.
Warning! Solutions using flatten will not preserve Array keys or values!
Building on #John Topley's popular answer, let's try:
a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]
This throws an error:
ArgumentError: odd number of arguments for Hash
from (irb):10:in `[]'
from (irb):10
The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.
If you want to use Array keys or values, you can use map:
h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"
This preserves the Array key:
h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}
The best way is to use Array#to_h:
[ [:apple,1],[:banana,2] ].to_h #=> {apple: 1, banana: 2}
Note that to_h also accepts a block:
[:apple, :banana].to_h { |fruit| [fruit, "I like #{fruit}s"] }
# => {apple: "I like apples", banana: "I like bananas"}
Note: to_h accepts a block in Ruby 2.6.0+; for early rubies you can use my backports gem and require 'backports/2.6.0/enumerable/to_h'
to_h without a block was introduced in Ruby 2.1.0.
Before Ruby 2.1, one could use the less legible Hash[]:
array = [ [:apple,1],[:banana,2] ]
Hash[ array ] #= > {:apple => 1, :banana => 2}
Finally, be wary of any solutions using flatten, this could create problems with values that are arrays themselves.
Update
Ruby 2.1.0 is released today. And I comes with Array#to_h (release notes and ruby-doc), which solves the issue of converting an Array to a Hash.
Ruby docs example:
[[:foo, :bar], [1, 2]].to_h # => {:foo => :bar, 1 => 2}
Edit: Saw the responses posted while I was writing, Hash[a.flatten] seems the way to go.
Must have missed that bit in the documentation when I was thinking through the response. Thought the solutions that I've written can be used as alternatives if required.
The second form is simpler:
a = [[:apple, 1], [:banana, 2]]
h = a.inject({}) { |r, i| r[i.first] = i.last; r }
a = array, h = hash, r = return-value hash (the one we accumulate in), i = item in the array
The neatest way that I can think of doing the first form is something like this:
a = [:apple, 1, :banana, 2]
h = {}
a.each_slice(2) { |i| h[i.first] = i.last }
You can also simply convert a 2D array into hash using:
1.9.3p362 :005 > a= [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
1.9.3p362 :006 > h = Hash[a]
=> {1=>2, 3=>4}
Summary & TL;DR:
This answer hopes to be a comprehensive wrap-up of information from other answers.
The very short version, given the data from the question plus a couple extras:
flat_array = [ apple, 1, banana, 2 ] # count=4
nested_array = [ [apple, 1], [banana, 2] ] # count=2 of count=2 k,v arrays
incomplete_f = [ apple, 1, banana ] # count=3 - missing last value
incomplete_n = [ [apple, 1], [banana ] ] # count=2 of either k or k,v arrays
# there's one option for flat_array:
h1 = Hash[*flat_array] # => {apple=>1, banana=>2}
# two options for nested_array:
h2a = nested_array.to_h # since ruby 2.1.0 => {apple=>1, banana=>2}
h2b = Hash[nested_array] # => {apple=>1, banana=>2}
# ok if *only* the last value is missing:
h3 = Hash[incomplete_f.each_slice(2).to_a] # => {apple=>1, banana=>nil}
# always ok for k without v in nested array:
h4 = Hash[incomplete_n] # or .to_h => {apple=>1, banana=>nil}
# as one might expect:
h1 == h2a # => true
h1 == h2b # => true
h1 == h3 # => false
h3 == h4 # => true
Discussion and details follow.
Setup: variables
In order to show the data we'll be using up front, I'll create some variables to represent various possibilities for the data. They fit into the following categories:
Based on what was directly in the question, as a1 and a2:
(Note: I presume that apple and banana were meant to represent variables. As others have done, I'll be using strings from here on so that input and results can match.)
a1 = [ 'apple', 1 , 'banana', 2 ] # flat input
a2 = [ ['apple', 1], ['banana', 2] ] # key/value paired input
Multi-value keys and/or values, as a3:
In some other answers, another possibility was presented (which I expand on here) – keys and/or values may be arrays on their own:
a3 = [ [ 'apple', 1 ],
[ 'banana', 2 ],
[ ['orange','seedless'], 3 ],
[ 'pear', [4, 5] ],
]
Unbalanced array, as a4:
For good measure, I thought I'd add one for a case where we might have an incomplete input:
a4 = [ [ 'apple', 1],
[ 'banana', 2],
[ ['orange','seedless'], 3],
[ 'durian' ], # a spiky fruit pricks us: no value!
]
Now, to work:
Starting with an initially-flat array, a1:
Some have suggested using #to_h (which showed up in Ruby 2.1.0, and can be backported to earlier versions). For an initially-flat array, this doesn't work:
a1.to_h # => TypeError: wrong element type String at 0 (expected array)
Using Hash::[] combined with the splat operator does:
Hash[*a1] # => {"apple"=>1, "banana"=>2}
So that's the solution for the simple case represented by a1.
With an array of key/value pair arrays, a2:
With an array of [key,value] type arrays, there are two ways to go.
First, Hash::[] still works (as it did with *a1):
Hash[a2] # => {"apple"=>1, "banana"=>2}
And then also #to_h works now:
a2.to_h # => {"apple"=>1, "banana"=>2}
So, two easy answers for the simple nested array case.
This remains true even with sub-arrays as keys or values, as with a3:
Hash[a3] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}
a3.to_h # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "pear"=>[4, 5]}
But durians have spikes (anomalous structures give problems):
If we've gotten input data that's not balanced, we'll run into problems with #to_h:
a4.to_h # => ArgumentError: wrong array length at 3 (expected 2, was 1)
But Hash::[] still works, just setting nil as the value for durian (and any other array element in a4 that's just a 1-value array):
Hash[a4] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
Flattening - using new variables a5 and a6
A few other answers mentioned flatten, with or without a 1 argument, so let's create some new variables:
a5 = a4.flatten
# => ["apple", 1, "banana", 2, "orange", "seedless" , 3, "durian"]
a6 = a4.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian"]
I chose to use a4 as the base data because of the balance problem we had, which showed up with a4.to_h. I figure calling flatten might be one approach someone might use to try to solve that, which might look like the following.
flatten without arguments (a5):
Hash[*a5] # => {"apple"=>1, "banana"=>2, "orange"=>"seedless", 3=>"durian"}
# (This is the same as calling `Hash[*a4.flatten]`.)
At a naïve glance, this appears to work – but it got us off on the wrong foot with the seedless oranges, thus also making 3 a key and durian a value.
And this, as with a1, just doesn't work:
a5.to_h # => TypeError: wrong element type String at 0 (expected array)
So a4.flatten isn't useful to us, we'd just want to use Hash[a4]
The flatten(1) case (a6):
But what about only partially flattening? It's worth noting that calling Hash::[] using splat on the partially-flattened array (a6) is not the same as calling Hash[a4]:
Hash[*a6] # => ArgumentError: odd number of arguments for Hash
Pre-flattened array, still nested (alternate way of getting a6):
But what if this was how we'd gotten the array in the first place?
(That is, comparably to a1, it was our input data - just this time some of the data can be arrays or other objects.) We've seen that Hash[*a6] doesn't work, but what if we still wanted to get the behavior where the last element (important! see below) acted as a key for a nil value?
In such a situation, there's still a way to do this, using Enumerable#each_slice to get ourselves back to key/value pairs as elements in the outer array:
a7 = a6.each_slice(2).to_a
# => [["apple", 1], ["banana", 2], [["orange", "seedless"], 3], ["durian"]]
Note that this ends up getting us a new array that isn't "identical" to a4, but does have the same values:
a4.equal?(a7) # => false
a4 == a7 # => true
And thus we can again use Hash::[]:
Hash[a7] # => {"apple"=>1, "banana"=>2, ["orange", "seedless"]=>3, "durian"=>nil}
# or Hash[a6.each_slice(2).to_a]
But there's a problem!
It's important to note that the each_slice(2) solution only gets things back to sanity if the last key was the one missing a value. If we later added an extra key/value pair:
a4_plus = a4.dup # just to have a new-but-related variable name
a4_plus.push(['lychee', 4])
# => [["apple", 1],
# ["banana", 2],
# [["orange", "seedless"], 3], # multi-value key
# ["durian"], # missing value
# ["lychee", 4]] # new well-formed item
a6_plus = a4_plus.flatten(1)
# => ["apple", 1, "banana", 2, ["orange", "seedless"], 3, "durian", "lychee", 4]
a7_plus = a6_plus.each_slice(2).to_a
# => [["apple", 1],
# ["banana", 2],
# [["orange", "seedless"], 3], # so far so good
# ["durian", "lychee"], # oops! key became value!
# [4]] # and we still have a key without a value
a4_plus == a7_plus # => false, unlike a4 == a7
And the two hashes we'd get from this are different in important ways:
ap Hash[a4_plus] # prints:
{
"apple" => 1,
"banana" => 2,
[ "orange", "seedless" ] => 3,
"durian" => nil, # correct
"lychee" => 4 # correct
}
ap Hash[a7_plus] # prints:
{
"apple" => 1,
"banana" => 2,
[ "orange", "seedless" ] => 3,
"durian" => "lychee", # incorrect
4 => nil # incorrect
}
(Note: I'm using awesome_print's ap just to make it easier to show the structure here; there's no conceptual requirement for this.)
So the each_slice solution to an unbalanced flat input only works if the unbalanced bit is at the very end.
Take-aways:
Whenever possible, set up input to these things as [key, value] pairs (a sub-array for each item in the outer array).
When you can indeed do that, either #to_h or Hash::[] will both work.
If you're unable to, Hash::[] combined with the splat (*) will work, so long as inputs are balanced.
With an unbalanced and flat array as input, the only way this will work at all reasonably is if the last value item is the only one that's missing.
Side-note: I'm posting this answer because I feel there's value to be added – some of the existing answers have incorrect information, and none (that I read) gave as complete an answer as I'm endeavoring to do here. I hope that it's helpful. I nevertheless give thanks to those who came before me, several of whom provided inspiration for portions of this answer.
Appending to the answer but using anonymous arrays and annotating:
Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]
Taking that answer apart, starting from the inside:
"a,b,c,d" is actually a string.
split on commas into an array.
zip that together with the following array.
[1,2,3,4] is an actual array.
The intermediate result is:
[[a,1],[b,2],[c,3],[d,4]]
flatten then transforms that to:
["a",1,"b",2,"c",3,"d",4]
and then:
*["a",1,"b",2,"c",3,"d",4] unrolls that into
"a",1,"b",2,"c",3,"d",4
which we can use as the arguments to the Hash[] method:
Hash[*("a,b,c,d".split(',').zip([1,2,3,4]).flatten)]
which yields:
{"a"=>1, "b"=>2, "c"=>3, "d"=>4}
if you have array that looks like this -
data = [["foo",1,2,3,4],["bar",1,2],["foobar",1,"*",3,5,:foo]]
and you want the first elements of each array to become the keys for the hash and the rest of the elements becoming value arrays, then you can do something like this -
data_hash = Hash[data.map { |key| [key.shift, key] }]
#=>{"foo"=>[1, 2, 3, 4], "bar"=>[1, 2], "foobar"=>[1, "*", 3, 5, :foo]}
Not sure if it's the best way, but this works:
a = ["apple", 1, "banana", 2]
m1 = {}
for x in (a.length / 2).times
m1[a[x*2]] = a[x*2 + 1]
end
b = [["apple", 1], ["banana", 2]]
m2 = {}
for x,y in b
m2[x] = y
end
For performance and memory allocation concerns please check my answer to Rails mapping array of hashes onto single hash where I bench-marked several solutions.
reduce / inject can be the fastest or the slowest solution depending on which method you use it which.
If the numeric values are seq indexes, then we could have simpler ways...
Here's my code submission, My Ruby is a bit rusty
input = ["cat", 1, "dog", 2, "wombat", 3]
hash = Hash.new
input.each_with_index {|item, index|
if (index%2 == 0) hash[item] = input[index+1]
}
hash #=> {"cat"=>1, "wombat"=>3, "dog"=>2}

Resources