Ruby

OptionParser

Ruby standard library to help creating command line apps with arguments parsing
1
require 'optparse'
2
​
3
options = {}
4
OptionParser.new do |opts|
5
opts.banner = "Usage: example.rb [options]"
6
​
7
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
8
options[:verbose] = v
9
end
10
end.parse!
11
​
12
p options
13
p ARGV
Copied!
​Read more​

String#unpack & Array#pack

Useful for reading & parsing binary or hexadecimal data.

String#unpack

Decodes string and returns array, according to template string given.
1
"ABC".unpack("H*") # Hex
2
=> ["414243"]
3
"ABC".unpack("H2")
4
=> ["41"]
5
"ABC".unpack("H2H2H2")
6
=> ["41", "42", "43"]
7
"ABC".unpack("U*") # Unicode
8
=> [65, 66, 67]
Copied!

Array#pack

Packs the contents of arr into a binary sequence, can reverse the unpack method.
1
["a", "b", "c"].pack("A")
2
=> "a"
3
["a", "b", "c"].pack("A3")
4
=> "a "
5
["a", "b", "c"].pack("A3A4A5")
6
=> "a b c "
7
[65, 66, 67].pack("U*")
8
=> "ABC"
9
["414243"].pack("H*")
10
=> "ABC"
11
["41", "42", "43"].pack("H2" * 3)
12
=> "ABC"
13
["ABCDE"].pack("m") # Base64 encode
14
=> "QUJDREU=\n"
Copied!
There are many directives to use building template strings. See Ruby docs for detail.

References

Last modified 1yr ago