Last active
April 14, 2017 00:09
-
-
Save the-nose-knows/784cd7216549972bf80ade8bd0db7fd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby - A nested hash example | |
# Load each pair of args on the command-line as a key-value pair | |
# For example from CMD.exe: | |
# call ruby.exe ruby_nested_hash_example.rb Age 30 Name Mary Fav_Hobby Ataraxia Fav_Number 42 | |
# Output would be: | |
# { | |
# "data_info": { | |
# "types": { | |
# "nums": { | |
# "Age": 30, | |
# "Fav_Number": 42 | |
# }, | |
# "strings": { | |
# "Name": "Mary", | |
# "Fav_Hobby": "Ataraxia" | |
# } | |
# }, | |
# "data_id": "13435436457" | |
# } | |
# } | |
if (ARGV.count % 2 != 0) || (ARGV.count < 2) | |
STDERR.puts "You must provide an even amount of command-line args to make key-value pairs.\n" | |
abort | |
end | |
require 'json' | |
cmd_hashes = {} | |
nums = {} | |
strings = {} | |
types = {} | |
#FYI `tl` == top-level | |
all_tl_keys = {} | |
data_info = {} | |
data_id = {:data_id => "13435436457"} | |
_key = "" | |
_value = "" | |
element = 0 | |
ARGV.each do |i| | |
if element % 2 == 0 | |
_key=i | |
else | |
if (i.to_i!=0) && (i!=0) | |
_value=i.to_i | |
else | |
_value=i | |
end | |
end | |
if (_key != "") && (_value != "") | |
cmd_hashes.store(_key, _value) | |
_key = "" | |
_value = "" | |
end | |
element+=1 | |
end | |
cmd_hashes.each do |key, value| | |
if value.is_a? Numeric | |
nums.store(key, value) | |
else | |
strings.store(key, value) | |
end | |
end | |
if nums.size > 0; types.merge!(:nums => nums) end | |
if strings.size > 0; types.merge!(:strings => strings) end | |
if types.size > 0; all_tl_keys.merge!(:types => types) end | |
if data_id.size > 0; all_tl_keys.merge!(data_id) end | |
if all_tl_keys.size > 0; data_info.merge!(:data_info => all_tl_keys) end | |
if data_info.size > 0; puts JSON.pretty_generate(data_info) end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment