forked from kbroman/ProgrammingNotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruby.txt
More file actions
387 lines (303 loc) · 9.17 KB
/
ruby.txt
File metadata and controls
387 lines (303 loc) · 9.17 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
Notes on Ruby
In ruby files (to make them executable), include:
#!/usr/bin/env ruby -v
To install rvm and ruby:
\curl -L https://get.rvm.io | bash -s stable --ruby
To install another version of ruby:
rvm install 2.0.0-p247
rvm use 2.0.0-p247 --default
To generate documentation
rvm docs generate
To update rvm
rvm get stable
Make sure rvm uses homebrew:
rvm autolibs homebrew
gem install roo # for parsing excel files
gem install wirble # syntax highlighting in irb
gem install gsl # gnu scientific library
gem install sciruby # sciruby [didn't completely work]
gem install bio # bioruby
Remove unnecessary old versions of gems:
gem cleanup
-----------
github pages install:
gem install github-pages
gem install bundler
bundle install
then
bundle exec jekyll serve
-----------
# copying arrays
a = [1,2,3]
b = a
c = a.dup
a.equal? b
!(a.equal? c)
# does a directory exist?
Dir.exists?("directory_name_here") # must be a _directory_
File.exists?("some_file_name")
# files in a directory
Dir.entries(".")
# select parts of an array
a = [2, 7, 5, 4]
b = a.select { |el| el > 4 }
# no list comprehension, but you can use select and map
x = [2, 7, 5, 4]
y = x.select{|e| e > 2}.map{|e| 2*e}
# one line if-else
x = 5
y = x > 3 ? x : 3
# item in array
x = ["a", "b", "c", "d"]
x.include?("e")
# sort strings as numbers
a = ['1', '12', '21', '3', '4']
a.sort_by(&:to_f)
# ternary operator
ifile = ARGV.length > 0 ? ARGV[0] : "ggplot2.Rmd"
# regular expression substitution
ofile = ifile.gsub(/(\.\w+)$/, '_slides\1')
# (so "blah.Rmd" becomes "blah_slides.Rmd")
# aborting
abort("file #{ofile} already exists") if File.exists?(ofile)
# adding to an array
x = [1, 2, 3]
x + [4, 5] # -> [1,2,3,4,5] (but x doesn't change)
x += [4,5] # -> x now is [1,2,3,4,5]
x.insert(1, -1) # -> [1,-1,2,3,4,5] (x is changed)
# hashes
x = {"name" => "karl", "age" => "really_old", "shoe_size"=> 8}
x["name"]
x.keys
x.values
x.has_key?('age') # check for specific key
# hash with symbols as the keys
y = {name: "karl", age: "really_old", shoe_size: 8} # no space between key and :
y[:name] # keys turned into symbols
y.keys
y.values
# combining array into string
x = ["a", "b", "c"]
x.join(',')
# set
require 'set'
x = Set.new()
x.add("a")
x.add("b")
x.add("a")
# convert array to set
x = ["A", "B", "C", "B"]
y = x.to_set()
y.delete("C") # delete item from set
# define function
def f(arg)
arg*2
end
# read lines from file
f = File.open("some_file.txt")
f.each_line do |line|
line.strip()
# do something else
end
# test whether something is nil
x = 5
x.nil?
y = nil
y.nil?
# do something to a bunch of files in a directory
# here, rename files like "myfile.txt" as "myfile_orig.txt"
dir = Dir.open(".")
dir.each do |file|
if file =~ /^(.*).txt$/
`mv #{file} #{$1}_orig.txt`
end
end
# convert enumerator to array
x = 5.upto(50).to_a
# .. vs ...
x = 5.upto(50).to_a
x[5..10] # include endpoint
x[5...10] # don't include endpoint
######################################################################
# various ruby stuff while I learn the language
# following Peter Cooper's Beginning Ruby
# loops
1.upto(9) { |x| print x}
puts
9.downto(5) { |x| print x}
puts
0.step(20, 5) { |x| print "#{x} " }
puts
# string methods
print "Length of \"This is a test\""
puts 'This is a test'.length
puts "This is a test".downcase
puts "This is a test".upcase
puts "This is a test".swapcase
puts "This is a test".reverse
# string manipulation & reg ex
puts "foobarfoobar".sub('bar', 'foo')
puts "foobarfoobar".gsub('bar', 'foo')
puts "This is a test".sub(/\s+/, '|')
puts "This is a test".gsub(/\s+/, '|')
# --- scan creates array of patterns and applies a function to each
"This is a test".scan(/\w\w/) { |x| puts x}
# --- match returns 'match' object
m = "This is a test".match(/(\w+) (\w+)/)
puts "#{m[0]}|#{m[1]}|#{m[2]}"
puts "Blah blah blah. ".split(/\s+/).inspect
# arrays
[1, "test", 2, 3, 4].each {|x| print "#{x}X " }
puts
[1, "test", 2, 3, 4].each {|x| print x.to_s + "Y " }
puts
# map (aka collect)
# [1, 2, 3, 4, 5, 6]
x = 1.upto(6).map {|x| x }
puts x.length
y = x.map { |x| x*2}
puts y.join(" ")
# ranges to arrays
x = 1.upto(6).to_a
y = (1..6).to_a
z = 3.step(50, 5).to_a
# loops
for i in 1..5
puts "#{i}^2 = #{i**2}"
end
i = 1
while i <= 5
puts "#{i}^2 = #{i**2}"
i += 1
end
i = 1
until i > 5
puts "#{i}^2 = #{i**2}"
i += 1
end
# other array methods
x = (1..5).to_a
y = [2, 4, 1]
puts (x + y).join(":")
puts (x - y).join(":")
puts (x-y).empty?
puts (x-y).include?(3)
puts (x-y).include?("x")
puts (x-y).first
puts (x-y).last
z = (5..8).to_a
puts z.last(2).join("-")
puts z.reverse
# hashes
x = {"a" => 1, "b" => 2, "c" => 3}
x.each {|key, value| puts "#{key} -> #{value}" }
puts x.keys.join(" ")
x.delete("a")
puts x
x = {"a" => 1, "b" => 2, "c" => 3}
x.delete_if {|key,value| value == 2}
puts x
# ? operator
age = 10
type = age < 18 ? "child" : "adult"
puts "age = #{age} -> #{type}"
# code_block as argument to function/method
def map_vowel(&code_block)
%w{a e i o u}.map {|v| code_block.call(v) }
end
puts map_vowel {|v| v*3} .join("|")
# equivalent to that?
def map_vowel2
%w{a e i o u}.map {|v| yield v}
end
puts map_vowel2 {|v| v*3} .join("|")
# saving a code block
block = lambda {|v| v*3}
# don't escape in strings: use arbitrary delimiters
x = 'blah'
y = %-#{x} says, "Blah, blah, blah."-
z = 'or this, "Blah, blah."'
w = %<#{x} says, "Blah, blah, blah.">
t = %q<#{x} says, "Blah, blah, blah.">
# slices of arrays, negative index to start from end
a = 2.step(12, 2).to_a
p a[1..3]
p a[-1]
p a[-3 .. -2]
# concatenate and append to arrays
x = []
x.concat(["a"])
x.concat(["b", "c"])
x.push(5)
x.push("hello")
# delete item from array
x = ["a", "b", "d"]
x.delete("b") # deletes this item
# search for element in array
x.include?("e") # true if "e" is in there; false if not
x.count("e") # number of times "e" appears in the array
# symbols (literal constants that can have arbitrary value...the name is the important thing)
# commonly used as keys for hashes
current_situation = :good
puts "Everything is fine" if current_situation == :good
puts "PANIC!" if current_situation == :bad
p person1 = { :name => "Fred", :age => 24, :gender => :male }
p person2 = { :name => "Ginger", :age => 18, :gender => :female }
# conversion between classes
"5".to_i # to integer
"6".to_f # to float
"blah".to_sym # to symbol
252.3.to_s # to string
# a bit of text manipulation
text = %q{We may at once admit that any inference from the particular to the general must be attended with some degree of uncertainty, but this is not the same as to admit that such inference cannot be absolutely rigorous, for the nature and degree of the uncertainty may itself be capable of rigorous expression.}
stopwords = %w{the a by on for of are with just but and to my in I has some}.map {|z| z.downcase}
words = text.downcase.scan(/\w+/)
keywords = words.select { |w| !stopwords.include?(w) }
puts keywords.join(" ")
puts %|no. char = #{keywords.join(" ").length}|
puts "no. words = #{keywords.length}"
# playing with map
n = 8
counts = 1.upto(n).map { 0 }
puts counts.join(" ")
x = 1.upto(1000).map {|z| rand(8)}
x.each {|z| counts[z] = counts[z] + 1 }
puts counts.join(" ")
# looping over hashes (also sorting)
words = %w{We may at once admit that any inference from the particular to the general must be attended with some degree of uncertainty, but this is not the same as to admit that such inference cannot be absolutely rigorous, for the nature and degree of the uncertainty may itself be capable of rigorous expression.}
words = words.map { |z| z.gsub(/[,\.]/, "") }
wordcount = {}
words.each { |z| wordcount[z] = wordcount[z].nil? ? 1 : wordcount[z] + 1 }
def by_count_and_length (a,b,hash)
return a.length <=> b.length if hash[a] == hash[b]
hash[a] <=> hash[b]
end
wordcount.keys.sort {|a,b| by_count_and_length(a,b,wordcount) }.each {|z| puts "#{z} => #{wordcount[z]}"}
# regex
puts "ok 1" if /AM/i =~ 'am'
puts "ok 2" if /\Ablah/ =~ "blah a number of special\nAll of these are"
puts "ok 3" unless /\AAll/ =~ "blah a number of special\nAll of these are"
puts "ok 4" if /^blah/ =~ "blah a number of special\nAll of these are"
puts "ok 5" if /^All/ =~ "blah a number of special\nAll of these are"
puts "ok 6" unless /special\z/ =~ "blah a number of special\nAll of these are"
puts "ok 7" if /are\z/ =~ "blah a number of special\nAll of these are"
puts "ok 8" if /special$/ =~ "blah a number of special\nAll of these are"
puts "ok 9" if /are$/ =~ "blah a number of special\nAll of these are"
puts "ok 10" unless /blah.*are/ =~ "blah a number of special\nAll of these are"
puts "ok 11" if /blah.*are/m =~ "blah a number of special\nAll of these are"
$x = "Today is 8/6/2013, while tomorrow is 8/7/2013."
if $x =~ /(\d+)\/(\d+)\/(\d+)/ # $~ contains info about
puts "Month = #{$~[1]}, day = #{$~[2]}, year = #{$~[3]}"
puts "Month = #{$1}, day = #{$2}, year = #{$3}"
puts $& # matched text
puts $` # text before the match
puts $' # text after the match
puts $+ # last bit of the match
end
# symbols and strings
the_string = :all.to_s
the_symbol = "all".to_sym
puts the_string.to_sym == the_symbol
puts the_string.to_sym.equal?(the_symbol)
puts the_symbol.to_s == the_string
puts (not the_symbol.to_s.equal?(the_string))