Reputation: 821
Ruby noob here....
I've been starring at hashes an arrays for too long.
I need to convert an Array like so...
myArray = ["X", "X", "O", "O", "O", "+", "+", "O", "X"]
into…a hash like so…
myHash = {"X"=>0, "X"=>1, "O"=>2, "O"=>3, "O"=>4, "+"=>5, "+"=>6, "O"=>7, "X"=>8}
How can I do this?
Thanks for your time.
Upvotes: 0
Views: 2105
Reputation: 80105
Actually this can be done:
myArray = ["X", "X", "O", "O", "O", "+", "+", "O", "X"]
h = {}.compare_by_identity
myArray.each_with_index{|k,v| h[k] = v}
p h
#=>{"X"=>0, "X"=>1, "O"=>2, "O"=>3, "O"=>4, "+"=>5, "+"=>6, "O"=>7, "X"=>8}
Upvotes: 4
Reputation: 114
I believe you did not quite get the grasp of Hashes or you simply want to destroy any Values that are duplicated.
Hashes cannot have duplicate keys, so 'X' cannot occure two times meaning: your hash will miss all duplicated keys in a conversion:
['X','X','Y'] -> {"X"=> 0, "Y"=>1} or {"X"=> 0, "Y"=>2}
This leads to another question: Do you want to work with the index or with incrementing integers starting at zero?
With index destroying any duplicates:
h = Hash.new
arr.each_with_index {|x,i| if not h.has_key?(x) then h[x] = i;h}
With increment also destroying any duplicates:
h = Hash.new
count = 0
arr.each{|x|
if not h.has_key?(x) then
h[x] = count
count+=1
}
This all can make sense but it really depends on the problem you would like to solve. As others suggested you could also reverse the order making the Integer your key.
A solution for Indices:
h = Hash.new
arr.each_with_index{|x,i|
h[i] = x
}
Hope any solution might work but for the future try to tell a bit more about the problem you would like to solve.
Upvotes: 0
Reputation: 302
looks like you want to deal somehow with the position of each element in the array
could be achieved with:
myHash = Hash.new
myArray.each_with_index do |x,i|
myHash[i] = x
end
myHash: => {0=>"X", 1=>"X", 2=>"O", 3=>"O", 4=>"O", 5=>"+", 6=>"+", 7=>"O", 8=>"X"}
Upvotes: 0
Reputation: 1334
harbichidian made a good point regarding the identical keys. To make a hash from an array in the format you specified:
myArray = ["X", "X", "O", "O", "O", "+", "+", "O", "X"]
myHash = {}
(0...myArray.length).each do |i|
myHash[myArray[i]] = i
end
However, since you have duplicate keys, this will result in:
{"X"=>8, "O"=>7, "+"=>6}
Upvotes: 0
Reputation: 21791
I assumed that you want an array, not a hash
["X", "X", "O", "O", "O", "+", "+", "O", "X"].each_with_index.map do |obj, i|
[obj,i]
end
=> [["X", 0], ["X", 1], ["O", 2], ["O", 3], ["O", 4], ["+", 5], ["+", 6], ["O", 7], ["X", 8]]
Upvotes: 0