Dir['*.js']
#=> ["diff.js", "index.js", "patch.js", "screen-buffer.js", "test-patch.js"]
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)
contents = File.read("/tmp/rgss/Game_Troop.rb")
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
if test =~ /def\s+(.+)/
# ^---^ => $1
p $1 #=> "initialize"
end
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],
contents.each_line do |line|
p line
end
File.write("/tmp/rgss/Game_Troop.html", "wtf")
# * 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