Skip to content

Instantly share code, notes, and snippets.

@LavirtheWhiolet
Created April 19, 2016 08:53
Show Gist options
  • Save LavirtheWhiolet/da75cbc7e3824192b77d6074dc122d1e to your computer and use it in GitHub Desktop.
Save LavirtheWhiolet/da75cbc7e3824192b77d6074dc122d1e to your computer and use it in GitHub Desktop.
Prints the value under specified keys or indexes of the YAML file.
#!/usr/bin/env ruby
require 'yaml'
def usage
puts <<-USAGE
Usage: #{File.basename __FILE__} [options] file {keys|indexes}
Prints the value under specified keys or indexes of the YAML file.
Options:
-h, --help Show this message and exit.
USAGE
end
while true
case ARGV.first
when "-h", "--help"
usage
exit
else
break
end
end
file = ARGV.shift
result = YAML.load(File.read(file))
until ARGV.empty?
key = ARGV.shift
old_result = result
result =
case result
when Array then begin result[Integer(key)] rescue nil end
when Hash then result[key]
end
if result.nil? then abort %(no key #{key} found in:\n#{old_result.to_yaml}); end
end
puts(
case result
when Hash then result.to_yaml
when Array then "[#{result.join(", ")}]"
else result
end
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment