-
Notifications
You must be signed in to change notification settings - Fork 0
/
ruby_cheats.rb
executable file
·92 lines (58 loc) · 1.59 KB
/
ruby_cheats.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# open/close file
f_ile = File.open("file.txt","w")
f_ile.write("hello world")
f_ile.close
# open file block method
File.open("file.txt","w") do |x|
x.write("hello file")
end
# read file block method
content = File.open("file.txt","r") do |x|
x.read
end
# Append to a file
File.open(File.expand_path("~/file.txt"), "a") do |f|
f << "hello append"
end
# For each line perform action
def load_file(file)
comics = {}
File.foreach(file) do |line|
name, url = line.split(': ')
comics[name] = url.strip
end
comics
end
comics = load_file("comics.txt")
# Directory and fileutils
# List files in directory
Dir.entries('/')
Dir['/*.txt']
# Copy a file
require "fileutils"
FileUtils.cp('/comics.txt', File.expand_path('~/comics.txt'))
# directory globbing
## count the files in my Downloads directory:
puts Dir.glob('Downloads/*').length #=> 382
## count all files in my Downloads directory and in sub-directories
puts Dir.glob('Downloads/**/*').length #=> 308858
## list just PDF files, either with .pdf or .PDF extensions:
puts Dir.glob('Downloads/*.{pdf,PDF}').join(",\n")
# download and write to file
require "open-uri"
kittens = open("http://placekitten.com/")
response_status = kittens.status
response_body = kittens.read[559,441]
puts response_status
puts response_body
kittenpic = open("http://placekitten.com/200/300")
File.open("kittens.jpg", "w") { |f| f.write(kittenpic) }
# parsing XML
require "open-uri"
require "rexml/document"
file = File.open("pets.txt")
doc = REXML::Document.new file
file.close
doc.elements.each("pets/pet/name") do |element|
puts element
end