johncorser
johncorser

Reputation: 9842

Writing values in hash to an array in a specific order

So I have a bunch of hashes that look like this

{
 "key1"=>"value1", 
 "key2"=>"value2", 
 "key4"=>"value4"
}

{
 "key1"=>"value1", 
 "key3"=>"value3", 
 "key4"=>"value4"
}

As you can see, not all of the hashes have all of the keys. Out of this, I need to get an array with all of the values, and the string "Not listed" in place of all of the missing values.

I started writing some code like this:

result = []
i = 0
hash.each do |key, value|
    i+=1
    result << value if key == "key" + i.to_s
end

before I realized that this strategy was not going to work. Any suggestions?

EDIT:

Expected output for the first hash would be

["value1", "value2", "Not Listed", "value4"]

and for the second hash would be

["value1", "Not Listed", "value3", "value4"]

Upvotes: 0

Views: 83

Answers (2)

Cheruvian
Cheruvian

Reputation: 5877

Initialize your hash with the default "not listed" then iterate through your input to populate values that are present.

def solution(keys,default_val)
  Hash[keys.product([default_val])]
end
result = solution(["key1","key2", "key3", "key4"],"not listed")
hash.each do |key, value|
  result[key] = value 
end

print(result)

Sorry just copied what user had.

Upvotes: 0

Uri Agassi
Uri Agassi

Reputation: 37409

It is not clear how you know how many keys there should be, but assuming you should have 4 keys, you could do the following:

h = {
 "key1"=>"value1", 
 "key2"=>"value2", 
 "key4"=>"value4"
}
(1..4).map { |i| h["key#{i}"] || 'Not Listed' }
#=> ["value1", "value2", "Not Listed", "value4"]

Arup suggested a different flavor, using fetch:

(1..4).map { |i| h.fetch("key#{i}", 'Not Listed') }
#=> ["value1", "value2", "Not Listed", "value4"]

Still another option is using Hash's default value:

h.default = 'Not Listed'
(1..4).map { |i| h["key#{i}"] }
#=> ["value1", "value2", "Not Listed", "value4"]

Upvotes: 6

Related Questions