Skip to content

Instantly share code, notes, and snippets.

@dtinth
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtinth/9171805 to your computer and use it in GitHub Desktop.
Save dtinth/9171805 to your computer and use it in GitHub Desktop.
Documentation Generation

Documentation Generation

How to scan directory

Dir['*.js']
#=> ["diff.js", "index.js", "patch.js", "screen-buffer.js", "test-patch.js"]

Filename manipulation

filename = "/tmp/hello/world/screen-buffer.js"
File.dirname(filename)        #=> "/tmp/hello/world" # (get directory name)
File.basename(filename)       #=> "screen-buffer.js" # (get only file name)
File.basename(filename, ".*") #=> "screen-buffer"    # (get only file name and remove extension)
File.extname(filename)        #=> ".js"              # (get only file extension)

How to read file

contents = File.read("/tmp/rgss/Game_Troop.rb")

Play with string

test = contents.lines[28]     #=> "  def initialize\n"
p test.chomp                  #=> "  def initialize"     # remove trailing newline
p test.strip                  #=> "def initialize"       # remove leading/trailing whitespace
p test.start_with?("#")       #=> false

Regular Expression: single matching

if test =~ /def\s+(.+)/
  #             ^---^ => $1
  p $1                        #=> "initialize"
end

Regular Expression: scanning

Using String#scan, it returns array of all matches.

p contents.scan(/def\s+.+/)
#=> ["def initialize", "def members", "def clear", "def troop", "def setup(troop_id)", ...

However, if the pattern contains "subpatterns", then String#scan returns array of array instead.

p contents.scan(/def\s+(.+)/)
#=> [["initialize"], ["members"], ["clear"], ["troop"], ["setup(troop_id)"], ...

p contents.scan(/def\s+([^\s\(]+)(.+)?/)
#=> [["initialize", nil],
#    ["members", nil],
#    ["clear", nil],
#    ["troop", nil],
#    ["setup", "(troop_id)"],
#    ["init_screen_tone", nil],

How to loop each line in string

contents.each_line do |line|
  p line
end

How to write file

All at once!

File.write("/tmp/rgss/Game_Troop.html", "wtf")

Line by line...

#                                     * w = write
File.open("/tmp/rgss/Game_Troop.html", "w") do |io|
  # io is a file object
  io << "hello"         # write string to file like in C++
  io.puts "world!"      # write string and add \n
  io.printf "%03d", 42  # printf like C
end
# file is closed automatically after the block is finished
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment