keysArr = ["a", "b", "c", "d", "e", "f"]
valuesArr = ["1", "2", "3", "4", "5", "6"]
keysStr = "a b c d e f"
valuesStr = "1,2,3,4,5,6"
h1 = Hash.new.add_pairs(keysArr,valuesArr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
h2 = Hash.new.add_pairs(keysStr,valuesStr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
h3 = Hash.new.add_pairs(keysArr,valuesStr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
h4 = Hash.new.add_pairs(keysStr,valuesArr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
keys = ["a", "b", "c", "d", "e", "f"]
vals = [1, 2, 3, 4, 5, 6]
h = Hash.new
while k = keys.shift and v = vals.shift
h[k] = v
end
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
keys
=> []
vals
=> []
require "hash_add_pairs"
keysArr = ["a", "b", "c", "d", "e", "f"]
valuesArr = ["1", "2", "3", "4", "5", "6"]
keysStr = "a b c d e f" WHITESPACE separated input string
valuesStr = "1,2,3,4,5,6" COMMA separated input string
# input from two Arrays:
h1 = Hash.new.add_pairs(keysArr,valuesArr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
# input from two Strings:
# please note that comma or space separated strings will be split automatically,
# without having to define a separator - commas have precedence over spaces.
# You can override this default-behaviour by explicitly defining a separator
h2 = Hash.new.add_pairs(keysStr,valuesStr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
newkeyStr = "first key,second key,third key,fourth key,fifth key, sixth key"
h = Hash.new.add_pairs(newKeyStr,valuesArr)
=> {"second key"=>"2", " sixth key"=>"6", "fifth key"=>"5", "first key"=>"1", "third key"=>"3", "fourth key"=>"4"}
# MIXED input from Array and String:
h3 = Hash.new.add_pairs(keysArr,valuesStr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
h4 = Hash.new.add_pairs(keysStr,valuesArr)
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
keysArr
=> ["a", "b", "c", "d", "e", "f"]
valuesArr
=> ["1", "2", "3", "4", "5", "6"]
keysStr
=> "a b c d e f"
valuesStr
=> "1,2,3,4,5,6"
# for Strings which are not using the commas or whitespace as separators:
# please note that this also works for mixed inputs
newKeys = "A:B:C:D:E:F"
newVals = "1:2:3:4:5:6"
h5 = Hash.new.add_pairs(newKeys,newVals,':') # both Strings have to use the same separators
=> {"A"=>"1", "B"=>"2", "C"=>"3", "D"=>"4", "E"=>"5", "F"=>"6"}
h6 = Hash.new.add_pairs(keysArr,newVals,':')
=> {"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4", "e"=>"5", "f"=>"6"}
h7 = Hash.new.add_pairs(newKeys,valuesArr,':')
=> {"A"=>"1", "B"=>"2", "C"=>"3", "D"=>"4", "E"=>"5", "F"=>"6"}
I'm not sure about the naming of those two methods yet - if you have suggestions how to rename them please contact me at
myFirstname dot myLastname at GMail.com
Please see the source code of the file for more details.