string = '\n' string = 'Jon \'Maddog\' Orwant'
string = "\n" string = "Jon \"Maddog\" Orwant"
string = %q/Jon 'Maddog' Orwant/
string = %q[Jon 'Maddog' Orwant] string = %q{Jon 'Maddog' Orwant} string = %q(Jon 'Maddog' Orwant) string = %q<Jon 'Maddog' Orwant>
a = <<"EOF"
This is a multiline here document
terminated by EOF on a line by itself
EOF
value = string[offset,count]
value = string[offset..-1]
string[offset,count] = newstring
string[offset..-1] = newtail
value = string[offset..offs2]
string[offset..offs2] = newstring
leading, s1, s2, trailing = data.unpack("A5 x3 A8 A8 A*")
fivers = string.unpack("A5" * (string.length/5))
chars = string.unpack("A1" * string.length)
string = "This is what you have"
first = string[0, 1] start = string[5, 2] rest = string[13..-1] last = string[-1, 1] end_ = string[-4..-1] piece = string[-8, 3]
string[5, 2] = "wasn't" string[-12..-1] = "ondrous" string[0, 1] = "" string[-10..-1] = ""
if string[-10..-1] =~ /pattern/
puts "Pattern matches in last 10 characters"
end
string[0, 5].gsub!(/is/, 'at')
a = "make a hat"
a[0, 1], a[-1, 1] = a[-1, 1], a[0, 1]
a = "To be or not to be"
b = a.unpack("x6 A6")
b, c = a.unpack("x6 A2 X5 A2")
puts "#{b}\n#{c}\n"
def cut2fmt(*args)
template = ''
lastpos = 1
for place in args
template += "A" + (place - lastpos).to_s + " "
lastpos = place
end
template += "A*"
return template
end
fmt = cut2fmt(8, 14, 20, 26, 30)
a = b || c
a = b.nonzero? || c
a = defined?(b) ? b : c
dir = ARGV.shift || "/tmp"
v1, v2 = v2, v1
alpha, beta, production = %w(January March August)
alpha, beta, production = beta, production, alpha
num = char[0]
char = num.chr
num = ?r
char = sprintf("%c", num)
printf("Number %d is character %c\n", num, num)
ascii = string.unpack("C*")
string = ascii.pack("C*")
hal = "HAL"
ascii = hal.unpack("C*")
ascii.collect! { |i|
i + 1 }
ibm = ascii.pack("C*")
puts ibm
array = string.split('')
array = string.unpack("C*")
string.scan(/./) { |b|
}
string = "an apple a day"
print "unique chars are: ", string.split('').uniq.sort, "\n"
sum = 0
for ascval in string.unpack("C*") sum += ascval
end
puts "sum is #{sum & 0xffffffff}"
delay = ARGV[0] =~ /^-([.\d]+)/ ? ARGV.shift && $1.to_i : 1
$stdout.sync = true
while gets
for b in split('')
print b
sleep(0.005 * delay)
end
end
revbytes = string.reverse
revwords = string.split(" ").reverse.join(" ")
revwords = string.split(/(\s+)/).reverse.join
long_palindromes = File.open("/usr/share/dict/words").
select { |w| w.chomp!; w.reverse == w && w.length > 5 }
while string.sub!("\t+") { ' ' * ($&.length * 8 - $`.length % 8) }
end
'You owe #{debt} to me'.gsub(/\#{(\w+)}/) { eval($1) }
rows, cols = 24, 80
text = %q(I am #{rows} high and #{cols} long)
text.gsub!(/\#{(\w+)}/) { eval("#{$1}") }
puts text
'I am 17 years old'.gsub(/\d+/) { 2 * $&.to_i }
e = "bo peep".upcase
e.downcase!
e.capitalize!
"thIS is a loNG liNE".gsub!(/\w+/) { $&.capitalize }
"I have #{n+1} guanacos."
print "I have ", n+1, " guanacos."
var = <<'EOF'.gsub(/^\s+/, '')
your text
goes here
EOF
string = "Folding and splicing is the work of an editor,\n"+
"not a mere collection of silicon\n"+
"and\n"+
"mobile electrons!"
def wrap(str, max_size)
all = []
line = ''
for l in str.split
if (line+l).length >= max_size
all.push(line)
line = ''
end
line += line == '' ? l : ' ' + l
end
all.push(line).join("\n")
end
print wrap(string, 20)
string = %q(Mom said, "Don't do that.")
string.gsub(/['"]/) { '\\'+$& }
string.gsub(/['"]/, '\&\&')
string.gsub(/[^A-Z]/) { '\\'+$& }
"is a test!".gsub(/\W/) { '\\'+$& }
string.strip!
def parse_csv(text)
new = text.scan(/"([^\"\\]*(?:\\.[^\"\\]*)*)",?|([^,]+),?|,/)
new << nil if text[-1] == ?,
new.flatten.compact
end
line = %q<XYZZY,"","O'Reilly, Inc","Wall, Larry","a \"glug\" bit,",5,"Error, Core Dumped">
fields = parse_csv(line)
fields.each_with_index { |v,i|
print "#{i} : #{v}\n";
}
require 'Soundex'
code = Text::Soundex.soundex(string)
codes = Text::Soundex.soundex(array)
def login_names
result = []
File.open("/etc/passwd") { |file|
file.each_line { |line|
next if line.match(/^#/)
cols = line.split(":")
result.push([cols[0], cols[4]])
}
}
result
end
puts "Lookup user: "
user = STDIN.gets
user.chomp!
exit unless user
name_code = Text::Soundex.soundex(user)
splitter = Regexp.new('(\w+)[^,]*\b(\w+)')
for username, fullname in login_names do
firstname, lastname = splitter.match(fullname)[1,2]
if name_code == Text::Soundex.soundex(username)
|| name_code == Text::Soundex.soundex(firstname)
|| name_code == Text::Soundex.soundex(lastname)
then
puts "#{username}: #{firstname} #{lastname}"
end
end
class Changer
def initialize(regex, subst)
@regex = Regexp.compile(regex)
@subst = subst
end
def change(string)
changed = string.gsub!(@regex, @subst)
if changed && $verbose
$stderr.puts("#{@regex.source} changed to #{@subst} at #{$FILENAME} line #{$.}")
end
end
end
def get_subs_from_end()
changelist = []
DATA.each do |line|
line.chomp!
(pat, subst) = line.split(/\s*=>\s*/)
if pat && subst
changelist.push(Changer.new(pat, subst))
end
end
changelist
end
changelist = get_subs_from_end()
if ARGV && ARGV[0] == "-v"
ARGV.shift
$verbose = true
else
$verbose = false
end
if ARGV.length > 0
$-i = ".orig" elsif test(?e, $stdin)
$stderr.puts("#{$0}:Reading from stdin")
end
while line = gets()
for changer in changelist
changer.change(line)
end
puts(line)
end
__END__
class PS
PS::Names = %w-flags uid pid ppid pri nice size
rss wchan stat tty time command-
PS::Names.each {|sym| attr_accessor sym}
attr_accessor :line
def set_fields
fields = line.split(" ",13)
PS::Names.each_with_index do |sym,i|
eval "self.#{sym} = " +
((0..7).include?(i) ? fields[i] : "'#{fields[i]}'")
end
end
end
raise <<USAGE unless ARGV.size > 0
usage: $0 criterion ...
#{PS::Names.join(" ")}
All criteria must be met for a line to be printed
USAGE
PS.class_eval <<CRITERIA
def is_desirable
$_ = line
#{ARGV.join(" and ")}
end
CRITERIA
ps = PS.new
File.popen("ps wwaxl") do |f|
puts f.gets
f.each do |ps.line|
ps.set_fields
print ps.line if ps.is_desirable
end
end
Integer("abc")
Integer("567")
Integer("56.7")
Float("56.7")
if string =~ /^[+-]?\d+$/
p 'is an integer'
else
p 'is not'
end
if string =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/
p 'is a decimal number'
else
p 'is not'
end
def equal(i, j, a)
sprintf("%.#{a}g", i) == sprintf("%.#{a}g", j)
end
wage = 536 week = 40 * wage printf("One week's wage is: \$%.2f\n", week/100.0)
num.round
a = 0.255
b = sprintf("%.2f", a)
print "Unrounded: #{a}\nRounded: #{b}\n"
printf "Unrounded: #{a}\nRounded: %.2f\n", a
print "number\tint\tfloor\tceil\n"
a = [ 3.3 , 3.5 , 3.7, -3.3 ]
for n in a
printf("% .1f\t% .1f\t% .1f\t% .1f\n", n, n.to_i, n.floor, n.ceil)
end
def dec2bin(n)
[n].pack("N").unpack("B32")[0].sub(/^0+(?=\d)/, '')
end
def bin2dec(n)
[("0"*32+n.to_s)[-32..-1]].pack("B32").unpack("N")[0]
end
for i in x .. y
end
x.step(y,7) { |i|
}
print "Infancy is: "
(0..2).each { |i|
print i, " "
}
print "\n"
class Integer
@@romanlist = [["M", 1000],
["CM", 900],
["D", 500],
["CD", 400],
["C", 100],
["XC", 90],
["L", 50],
["XL", 40],
["X", 10],
["IX", 9],
["V", 5],
["IV", 4],
["I", 1]]
def to_roman
remains = self
roman = ""
for sym, num in @@romanlist
while remains >= num
remains -= num
roman << sym
end
end
roman
end
def Integer.from_roman(roman)
ustr = roman.upcase
sum = 0
for entry in @@romanlist
sym, num = entry[0], entry[1]
while sym == ustr[0, sym.length]
sum += num
ustr.slice!(0, sym.length)
end
end
sum
end
end
roman_fifteen = 15.to_roman
puts "Roman for fifteen is #{roman_fifteen}"
i = Integer.from_roman(roman_fifteen)
puts "Converted back, #{roman_fifteen} is #{i}"
for i in (1..3900)
r = i.to_roman
j = Integer.from_roman(r)
if i != j
puts "error: #{i} : #{r} - #{j}"
end
end
random = rand(y-x+1)+x
chars = ["A".."Z","a".."z","0".."9"].collect { |r| r.to_a }.join + %q(!@$%^&*)
password = (1..8).collect { chars[rand(chars.size)] }.pack("C*")
srand srand(val)
----> http://raa.ruby-lang.org/project/randomr/
require 'random/mersenne_twister'
mers = Random::MersenneTwister.new 123456789
puts mers.rand(0) puts mers.rand(10)
require 'random/online'
generator1 = Random::RandomOrg.new
puts generator1.randbyte(5).join(",")
puts generator1.randnum(10, 1, 6).join(",")
generator2 = Random::FourmiLab.new
puts generator2.randbyte(5).join(",")
generator3 = Random::EntropyPool.new
puts generator3.randbyte(5).join(",")
def gaussian_rand
begin
u1 = 2 * rand() - 1
u2 = 2 * rand() - 1
w = u1*u1 + u2*u2
end while (w >= 1)
w = Math.sqrt((-2*Math.log(w))/w)
[ u2*w, u1*w ]
end
mean = 25
sdev = 2
salary = gaussian_rand[0] * sdev + mean
printf("You have been hired at \$%.2f\n", salary)
def deg2rad(d)
(d/180.0)*Math::PI
end
def rad2deg(r)
(r/Math::PI)*180
end
sin_val = Math.sin(angle)
cos_val = Math.cos(angle)
tan_val = Math.tan(angle)
module Math
def Math.asin(x)
atan2(x, sqrt(1 - x**2))
end
def Math.acos(x)
atan2(sqrt(1 - x**2), x)
end
def Math.atan(x)
atan2(x, 1)
end
def Math.sinh(x)
(exp(x) - exp(-x)) / 2
end
def Math.cosh(x)
(exp(x) + exp(-x)) / 2
end
def Math.tanh(x)
sinh(x) / cosh(x)
end
end
y = Math.acos(3.7)
log_e = Math.log(val)
log_10 = Math.log10(val)
def log_base(base, val)
Math.log(val)/Math.log(base)
end
answer = log_base(10, 10_000)
puts "log10(10,000) = #{answer}"
require 'matrix.rb'
a = Matrix[[3, 2, 3], [5, 9, 8]]
b = Matrix[[4, 7], [9, 3], [8, 1]]
c = a * b
a.row_size
a.column_size
c.det
a.transpose
require 'complex.rb'
require 'rational.rb'
a = Complex(3, 5) b = Complex(2, -2) puts "c = #{a*b}"
c = a * b
d = 3 + 4*Complex::I
printf "sqrt(#{d}) = %s\n", Math.sqrt(d)
number = hexadecimal.hex
number = octal.oct
print "Gimme a number in decimal, octal, or hex: "
num = gets.chomp
exit unless defined?(num)
num = num.oct if num =~ /^0/ printf "%d %x %o\n", num, num, num
print "Enter file permission in octal: "
permissions = gets.chomp
raise "Exiting ...\n" unless defined?(permissions)
puts "The decimal value is #{permissions.oct}"
def commify(n)
n.to_s =~ /([^\.]*)(\..*)?/
int, dec = $1.reverse, $2 ? $2 : ""
while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
end
int.reverse + dec
end
printf "It took %d hour%s\n", time, time == 1 ? "" : "s"
def factorize(orig)
factors = {}
factors.default = 0 n = orig
i = 2
sqi = 4 while sqi <= n do
while n.modulo(i) == 0 do
n /= i
factors[i] += 1
#{i} end
sqi += 2 * i + 1
i += 1
end
if (n != 1) && (n != orig)
factors[n] += 1
end
factors
end
def printfactorhash(orig, factorcount)
print format("%-10d ", orig)
if factorcount.length == 0
print "PRIME"
else
factorcount.sort.each { |factor,exponent|
print factor
if exponent > 1
print "**", exponent
end
print " "
}
end
puts
end
for arg in ARGV
n = arg.to_i
mfactors = factorize(n)
printfactorhash(n, mfactors)
end
puts Time.now
print "Today is day ", Time.now.yday, " of the current year.\n"
print "Today is day ", Time.now.day, " of the current month.\n"
day, month, year = Time.now.day, Time.now.month, Time.now.year
day, month, year = Time.now.to_a[3..5]
tl = Time.now.localtime
printf("The current date is %04d %02d %02d\n", tl.year, tl.month, tl.day)
Time.now.localtime.strftime("%Y-%m-%d")
Time.local(year, month, day, hour, minute, second).tv_sec
Time.gm(year, month, day, hour, minute, second).tv_sec
sec, min, hour, day, month, year, wday, yday, isdst, zone = Time.at(epoch_secs).to_a
when_ = now + difference then_ = now - difference
bree = 361535725
nat = 96201950
difference = bree - nat
puts "There were #{difference} seconds between Nat and Bree"
seconds = difference % 60
difference = (difference - seconds) / 60
minutes = difference % 60
difference = (difference - minutes) / 60
hours = difference % 24
difference = (difference - hours) / 24
days = difference % 7
weeks = (difference - days) / 7
puts "(#{weeks} weeks, #{days} days, #{hours}:#{minutes}:#{seconds})"
monthday, weekday, yearday = date.mday, date.wday, date.yday
weeknum = d.strftime("%U").to_i + 1
year = 1981
month = "jun" day = 16
t = Time.mktime(year, month, day)
print "#{month}/#{day}/#{year} was a ", t.strftime("%A"), "\n"
yyyy, mm, dd = $1, $2, $3 if "1998-06-25" =~ /(\d+)-(\d+)-(\d+)/
epoch_seconds = Time.mktime(yyyy, mm, dd).tv_sec
string = Time.at(epoch_secs)
Time.at(1234567890).gmtime
time = Time.mktime(1973, "jan", 18, 3, 45, 50)
print "In localtime it gives: ", time.localtime, "\n"
Time.now.usec
before = Time.now
line = gets
elapsed = Time.now - before
puts "You took #{elapsed} seconds."
size = 500
number_of_times = 100
total_time = 0
number_of_times.times {
array = []
size.times { array << rand }
begin_ = Time.now
array.sort!
time = Time.now - begin_
total_time += time
}
printf "On average, sorting %d random numbers takes %.5f seconds\n",
size, (total_time/Float(number_of_times))
sleep(0.005)
require 'time'
class MailHopDelta
def initialize(mail)
@head = mail.gsub(/\n\s+/,' ')
@topline = %w-Sender Recipient Time Delta-
@start_from = mail.match(/^From.*\@([^\s>]*)/)[1]
@date = Time.parse(mail.match(/^Date:\s+(.*)/)[1])
end
def out(line)
"%-20.20s %-20.20s %-20.20s %s" % line
end
def hop_date(day)
day.strftime("%I:%M:%S %Y/%m/%d")
end
def puts_hops
puts out(@topline)
puts out(['Start', @start_from, hop_date(@date),''])
@head.split(/\n/).reverse.grep(/^Received:/).each do |hop|
hop.gsub!(/\bon (.*?) (id.*)/,'; \1')
whence = hop.match(/;\s+(.*)$/)[1]
unless whence
warn "Bad received line: #{hop}"
next
end
from = $+ if hop =~ /from\s+(\S+)|\((.*?)\)/
by = $1 if hop =~ /by\s+(\S+\.\S+)/
next unless now = Time.parse(whence).localtime
delta = now - @date
puts out([from, by, hop_date(now), hop_time(delta)])
@date = now
end
end
def hop_time(secs)
sign = secs < 0 ? -1 : 1
days, secs = secs.abs.divmod(60 * 60 * 24)
hours,secs = secs.abs.divmod(60 * 60)
mins, secs = secs.abs.divmod(60)
rtn = "%3ds" % [secs * sign]
rtn << "%3dm" % [mins * sign] if mins != 0
rtn << "%3dh" % [hours * sign] if hours != 0
rtn << "%3dd" % [days * sign] if days != 0
rtn
end
end
$/ = ""
mail = MailHopDelta.new(ARGF.gets).puts_hops
single_level = [ "this", "that", "the", "other" ]
double_level = [ "this", "that", [ "the", "other" ] ]
still_single_level = [ "this", "that", [ "the", "other" ] ].flatten
a = [ "quick", "brown", "fox" ]
a = %w(Why are you teasing me?)
lines = <<"END_OF_HERE_DOC".gsub(/^\s*(.+)/, '\1')
The boy stood on the burning deck,
It was as hot as glass.
END_OF_HERE_DOC
bigarray = IO.readlines("mydatafile").collect { |l| l.chomp }
name = "Gandalf"
banner = %Q(Speak, #{name}, and welcome!)
host_info = `host #{his_host}`
%x(ps #{$$})
banner = 'Costs only $4.95'.split(' ')
rax = %w! ( ) < > { } [ ] !
def commify_series(arr)
return '' if not arr
case arr.size
when 0 then ''
when 1 then arr[0]
when 2 then arr.join(' and ')
else arr[0..-2].join(', ') + ', and ' + arr[-1]
end
end
array = [ "red", "yellow", "green" ]
print "I have ", array, " marbles\n"
print "I have #{array} marbles\n"
print "I have #{array.join(' ')} marbles\n"
def commify_series(arr)
return '' if not arr
sepchar = arr.find { |p| p =~ /,/ } ? '; ' : ', '
case arr.size
when 0 then ''
when 1 then arr[0]
when 2 then arr.join(' and ')
else arr[0..-2].join(sepchar) + sepchar + 'and ' + arr[-1]
end
end
lists = [
[ 'just one thing' ],
%w(Mutt Jeff),
%w(Peter Paul Mary),
[ 'To our parents', 'Mother Theresa', 'God' ],
[ 'pastrami', 'ham and cheese', 'peanut butter and jelly', 'tuna' ],
[ 'recycle tired, old phrases', 'ponder big, happy thoughts' ],
[ 'recycle tired, old phrases',
'ponder big, happy thoughts',
'sleep and dream peacefully' ],
]
for list in lists do
puts "The list is: #{commify_series(list)}."
end
ary[new_size-1] = nil
ary.slice!(new_size..-1)
Array.new(number_of_elems)
ary[index_new_last_elem] = value
def what_about_that_array(a)
print "The array now has ", a.size, " elements.\n"
print "Element #3 is `#{a[3]}'.\n"
end
people = %w(Crosby Stills Nash Young)
what_about_that_array(people)
bad_users.each { |user|
complain(user)
}
for user in bad_users
complain(user)
end
for var in ENV.keys.sort
puts "#{var}=#{ENV[var]}"
end
for user in all_users
disk_space = get_usage(user)
if (disk_space > MAX_QUOTA)
complain(user)
end
end
for l in IO.popen("who").readlines
print l if l =~ /^gc/
end
while fh.gets chomp split.each { |w| print w.reverse
}
end
for l in fh.readlines
l.chomp.split.each { |w| print w.reverse }
end
array.collect! { |v| v - 1 }
a = [ .5, 3 ]; b = [ 0, 1 ]
for ary in [ a, b ]
ary.collect! { |v| v * 7 }
end
puts "#{a.join(' ')} #{b.join(' ')}"
for ary in [ [ scalar ], array, hash.values ]
ary.each { |v| v.strip! } end
for item in array
end
unique = list.uniq
users = `who`.collect { |l| l =~ /(\w+)/; $1 }.sort.uniq
puts("users logged in: #{commify_series(users)}")
a - b
union = a | b
intersection = a & b
difference = a - b
array1.concat(array2)
new_ary = array1 + array2
members = [ "Time", "Flies" ]
initiates = [ "An", "Arrow" ]
members += initiates
members = [ "Time", "Flies" ]
initiates = [ "An", "Arrow" ]
members[2,0] = [ "Like", initiates ].flatten
members[0] = "Fruit"
members[3,2] = "A", "Banana"
reversed = ary.reverse
ary.reverse_each { |e|
}
descending = ary.sort.reverse
descending = ary.sort { |a,b| b <=> a }
front = ary.slice!(0, n)
end_ = ary.slice!(-n .. -1)
class Array
def shift2()
slice!(0 .. 1) end
def pop2()
slice!(-2 .. -1)
end
end
friends = %w(Peter Paul Mary Jim Tim)
this, that = friends.shift2
beverages = %w(Dew Jolt Cola Sprite Fresca)
pair = beverages.pop2
highest_eng = employees.detect { |emp| emp.category == 'engineer' }
bigs = nums.select { |i| i > 1_000_000 }
pigs = users.keys.select { |k| users[k] > 1e7 }
matching = `who`.select { |u| u =~ /^gnat / }
engineers = employees.select { |e| e.position == 'Engineer' }
secondary_assistance = applicants.select { |a|
a.income >= 26_000 && a.income < 30_000
}
sorted = unsorted.sort
sorted = unsorted.sort { |a,b| a.to_f <=> b.to_f }
`ps ux`.split("\n")[1..-1].
select { |i| i =~ /^#{ENV['USER']}/ }.
collect { |i| i.split[1] }.
sort { |a,b| a.to_i <=> b.to_i }.each { |i| puts i }
puts "Select a process ID to kill:"
pid = gets.chomp
raise "Exiting ... \n" unless pid && pid =~ /^\d+$/
Process.kill('TERM', pid.to_i)
sleep 2
Process.kill('KILL', pid.to_i)
descending = unsorted.sort { |a,b| b.to_f <=> a.to_f }
ordered = unordered.sort { |a,b| compare(a,b) }
precomputed = unordered.collect { |e| [compute, e] }
ordered_precomputed = precomputed.sort { |a,b| a[0] <=> b[0] }
ordered = ordered_precomputed.collect { |e| e[1] }
ordered = unordered.collect { |e| [compute, e] }.
sort { |a,b| a[0] <=> b[0] }.
collect { |e| e[1] }
for employee in employees.sort { |a,b| a.name <=> b.name }
print employee.name, " earns \$ ", employee.salary, "\n"
end
sorted = employees.sort { |a,b| (a.name <=> b.name).nonzero? || b.age <=> a.age }
users = []
IO.readlines('/etc/passwd').each { |u| users << u.split(':') }
users.sort! { |a,b| a[0] <=> b[0] }
for user in users
puts user[0]
end
sorted = names.sort { |a,b| a[1, 1] <=> b[1, 1] }
sorted = strings.sort { |a,b| a.length <=> b.length }
ordered = strings.collect { |e| [e.length, e] }.
sort { |a,b| a[0] <=> b[0] }.
collect { |e| e[1] }
ordered = strings.collect { |e| [/\d+/.match(e)[0].to_i, e] }.
sort { |a,b| a[0] <=> b[0] }.
collect { |e| e[1] }
print `cat /etc/passwd`.collect { |e| [e, e.split(':').indexes(3,2,0)].flatten }.
sort { |a,b| (a[1] <=> b[1]).nonzero? || (a[2] <=> b[2]).nonzero? || a[3] <=> b[3] }.
collect { |e| e[0] }
circular.unshift(circular.pop) circular.push(circular.shift)
def grab_and_rotate(l)
l.push(ret = l.shift)
ret
end
processes = [1, 2, 3, 4, 5]
while (1)
process = grab_and_rotate(processes)
puts "Handling process #{process}"
sleep 1
end
def fisher_yates_shuffle(a)
(a.size-1).downto(1) { |i|
j = rand(i+1)
a[i], a[j] = a[j], a[i] if i != j
}
end
def naive_shuffle(a)
for i in 0...a.size
j = rand(a.size)
a[i], a[j] = a[j], a[i]
end
end
class WordFormatter
def initialize(cols)
@cols = cols
end
def maxlen(wordlist)
max = 1
for word in wordlist
if word.length > max
max = word.length
end
end
max
end
def output(wordlist)
collen = maxlen(wordlist) + 1
columns = @cols / collen
columns = 1 if columns == 0
rows = (wordlist.length + columns - 1) / columns
0.upto(rows * columns - 1) { |item|
target = (item % columns) * rows + (item / columns)
eol = ((item+1) % columns == 0)
piece = wordlist[target] || ""
piece = piece.ljust(collen) unless eol
print piece
puts if eol
}
end
end
def getWinCharWidth()
buf = "\0" * 8
$stdout.ioctl(0x5413, buf)
ws_row, ws_col, ws_xpixel, ws_ypixel = buf.unpack("$4")
ws_col || 80
rescue
80
end
cols = getWinCharWidth()
formatter = WordFormatter.new(cols)
words = readlines()
words.collect! { |line|
line.chomp
}
formatter.output(words)
def factorial(n)
s = 1
while n > 0
s *= n
n -= 1
end
s
end
puts factorial(500)
def permute(items, perms)
unless items.length > 0
puts perms.join(" ")
else
for i in items
newitems = items.dup
newperms = perms.dup
newperms.unshift(newitems.delete(i))
permute(newitems, newperms)
end
end
end
permute(ARGV, [])
def factorial(n)
s = 1
while n > 0
s *= n
n -= 1
end
s
end
class Factorial
@@fact = [ 1 ]
def Factorial.compute(n)
if @@fact[n]
@@fact[n]
else
@@fact[n] = n * Factorial.compute(n - 1)
end
end
end
def n2pat(n, length)
pat = []
i = 1
while i <= length
pat.push(n % i)
n /= i
i += 1
end
pat
end
def pat2perm(pat)
source = (0 .. pat.length - 1).to_a
perm = []
perm.push(source.slice!(pat.pop)) while pat.length > 0
perm
end
def n2perm(n, len)
pat2perm(n2pat(n,len))
end
while gets
data = split
num_permutations = Factorial.compute(data.length())
0.upto(num_permutations - 1) do |i|
permutation = n2perm(i, data.length).collect {
|j| data[j]
}
puts permutation.join(" ")
end
end
age = { "Nat", 24,
"Jules", 25,
"Josh", 17 }
age["Nat"] = 24
age["Jules"] = 25
age["Josh"] = 17
food_color = {
"Apple" => "red",
"Banana" => "yellow",
"Lemon" => "yellow",
"Carrot" => "orange"
}
hash[key] = value
food_color["Raspberry"] = "pink"
puts "Known foods:", food_color.keys
if (hash.has_key?(key))
else
end
[ "Banana", "Martini" ].each { |name|
print name, " is a ", food_color.has_key?(name) ? "food" : "drink", "\n"
}
age = {}
age['Toddler'] = 3
age['Unborn'] = 0
age['Phantasm'] = nil
for thing in ['Toddler', 'Unborn', 'Phantasm', 'Relic']
print "#{thing}: "
print "Has-key " if age.has_key?(thing)
print "True " if age[thing]
print "Nonzero " if age[thing] && age[thing].nonzero?
print "\n"
end
food_color.delete("Banana")
hash.each { |key, value|
}
hash.each_key { |key|
}
food_color.each { |food, color|
puts "#{food} is #{color}"
}
food_color.each_key { |food|
puts "#{food} is #{food_color[food]}"
}
food_color.keys.sort.each { |food|
puts "#{food} is #{food_color[food]}."
}
from = Hash.new(0)
while gets
/^From: (.*)/ and from[$1] += 1
end
from.sort {|a,b| b[1]<=>a[1]}.each { |v|
puts "#{v[1]}: #{v[0]}"
}
p hash
hash.each { |k,v| puts "#{k} => #{v}" }
hash.sort.each { |e| puts "#{e[0]} => #{e[1]}" }
hash.sort{|a,b| a[1]<=>b[1]}.each { |e| puts "#{e[0]} => #{e[1]}" }
require 'rubygems'
require 'ordered_hash'
hash = OrderedHash.new;
keys = hash.keys
require 'rubygems'
require 'ordered_hash'
food_color = OrderedHash.new
food_color["Banana"] = "Yellow"
food_color["Apple"] = "Green"
food_color["Lemon"] = "Yellow"
puts "In insertion order, the foods are:"
food_color.each_key { |food|
puts " #{food}"
}
puts "Still in insertion order, the foods' colors are:"
food_color.each { |food, color|
puts "#{food} is colored #{color}."
}
ttys = Hash.new
for i in `who`
user, tty = i.split
(ttys[user] ||= []) << tty end
ttys.keys.sort.each { |k|
puts "#{k}: #{commify_series(ttys[k])}" }
surname = { "Mickey" => "Mantle", "Babe" => "Ruth" }
puts surname.index("Mantle")
given = ARGV.shift or raise "usage: foodfind food_or_color"
color = {
"Apple" => "red",
"Banana" => "yellow",
"Lemon" => "yellow",
"Carrot" => "orange",
}
if (color.has_key?(given))
puts "#{given} is a food with color #{color[given]}."
end
if (color.has_value?(given))
puts "#{color.index(given)} is a food with color #{given}."
end
food_color.sort.each { |f|
puts "#{f[0]} is #{f[1]}."
}
food_color.sort { |a,b| a[1] <=> b[1] }.each { |f|
puts "#{f[0]} is #{f[1]}."
}
food_color.sort { |a,b| a[1].length <=> b[1].length }.each { |f|
puts "#{f[0]} is #{f[1]}."
}
merged = a.clone.update(b)
drink_color = { "Galliano" => "yellow", "Mai Tai" => "blue" }
ingested_color = drink_color.clone.update(food_color)
substance_color = {}
for i in [ food_color, drink_color ]
i.each_key { |k|
if substance_color.has_key?(k)
puts "Warning: #{k} seen twice. Using the first definition."
next
end
substance_color[k] = 1
}
end
common = hash1.keys & hash2.keys
this_not_that = hash1.keys - hash2.keys
count = Hash.new(0)
array.each { |e|
count[e] += 1
}
father = {
"Cain" , "Adam",
"Abel" , "Adam",
"Seth" , "Adam",
"Enoch" , "Cain",
"Irad" , "Enoch",
"Mehujael" , "Irad",
"Methusael" , "Mehujael",
"Lamech" , "Methusael",
"Jabal" , "Lamech",
"Jubal" , "Lamech",
"Tubalcain" , "Lamech",
"Enos" , "Seth",
}
while gets
chomp
begin
print $_, " "
end while $_ = father[$_]
puts
end
children = {}
father.each { |k,v|
(children[v] ||= []) << k
}
while gets
chomp
puts "#{$_} begat #{(children[$_] || ['Nobody']).join(', ')}.\n"
end
includes = {}
files.each { |f|
begin
for l in IO.readlines(f)
next unless l =~ /^\s*#\s*include\s*<([^>]+)>/
(includes[$1] ||= []) << f
end
rescue SystemCallError
$stderr.puts "#$! (skipping)"
end
}
include_free = includes.values.flatten.uniq - includes.keys
class DuNode
attr_reader :name
attr_accessor :size
attr_accessor :kids
def initialize(name)
@name = name
@kids = []
@size = 0
end
def size_compare(node2)
@size <=> node2.size
end
def basename
@name.sub(/.*\//, "")
end
def parent
p = @name.sub(/\/[^\/]+$/,"")
if p == @name
nil
else
p
end
end
end
class Dutree
attr_reader :topdir
def initialize
@nodes = Hash.new
@dirsizes = Hash.new(0)
@kids = Hash.new([])
end
def get_create_node(name)
if @nodes.has_key?(name)
@nodes[name]
else
node = DuNode.new(name)
@nodes[name] = node
node
end
end
def input(arguments)
name = ""
cmd = "du " + arguments.join(" ")
IO.popen(cmd) { |pipe|
pipe.each { |line|
size, name = line.chomp.split(/\s+/, 2)
node = get_create_node(name)
node.size = size.to_i
@nodes[name] = node
parent = node.parent
if parent
get_create_node(parent).kids.push(node)
end
}
}
@topdir = @nodes[name]
end
def get_dots(node)
cursize = node.size
for kid in node.kids
cursize -= kid.size
get_dots(kid)
end
if node.size != cursize
newnode = get_create_node(node.name + "/.")
newnode.size = cursize
node.kids.push(newnode)
end
end
def output(node, prefix="", width=0)
line = sprintf("%#{width}d %s", node.size, node.basename)
puts(prefix + line)
prefix += line.sub(/\d /, "| ")
prefix.gsub!(/[^|]/, " ")
if node.kids.length > 0 kids = node.kids
kids.sort! { |a,b|
b.size_compare(a)
}
width = kids[0].size.to_s.length
for kid in kids
output(kid, prefix, width)
end
end
end
end
tree = Dutree.new
tree.input(ARGV)
tree.get_dots(tree.topdir)
tree.output(tree.topdir)
pattern.match(string)
string.sub(pattern, replacement)
string.gsub(pattern, replacement)
meadow =~ /sheep/ meadow !~ /sheep/
meadow =~ /\bovines?\b/i and print "Here be sheep!"
string = "good food"
string.sub!(/o*/, 'e')
scan (/(\d+)/) {
puts "Found number #{$1}"
}
numbers = scan(/\d+/)
digits = "123456789"
nonlap = digits.scan(/(\d\d\d)/)
yeslap = digits.scan(/(?=(\d\d\d))/)
puts "Non-overlapping: #{nonlap.join(' ')}"
puts "Overlapping: #{yeslap.join(' ')}";
string = "And little lambs eat ivy"
string =~ /l[^s]*s/
puts "(#$`) (#$&) (#$')"
dst = src.sub('this', 'that')
progname = $0.sub('^.*/', '')
bindirs = %w(/usr/bin /bin /usr/local/bin)
libdirs = bindirs.map { |l| l.sub('bin', 'lib') }
/\S+/ /[A-Za-z'-]+/
/\b([A-Za-z]+)\b/ /\s([A-Za-z]+)\s/
require 'socket'
str = 'www.ruby-lang.org and www.rubygarden.org'
re = /
( (?: (?! [-_] ) [\w-] + \. ) + [A-Za-z] [\w-] + ) /x # /x for nice formatting
str.gsub! re do host = TCPsocket.gethostbyname($1)
"#{$1} [#{host[3]}]"
end
puts str
foo = 42
str = 'blah #foo# blah'
str.gsub! %r/ \# (\w+) \# /x do
eval $1 end
puts str
fish = 'One fish two fish red fish blue fish'
WANT = 3
count = 0
fish.scan(/(\w+)\s+fish\b/i) {
if (count += 1) == WANT
puts "The third fish is a #{$1} one."
end
}
if fish =~ /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i
puts "The third fish is a #{$1} one."
end
pond = 'One fish two fish red fish blue fish'
colors = pond.scan(/(\w+)\s+fish\b/i).flatten color = colors[2] color = pond.scan(/(\w+)\s+fish\b/i).flatten[2] puts "The third fish in the pond is #{color}."
count = 0
fishes = 'One fish two fish red fish blue fish'
evens = fishes.scan(/(\w+)\s+fish\b/i).select { (count+=1) % 2 == 0 }
print "Even numbered fish are #{evens.join(' ')}."
count = 0
fishes.gsub(/
\b ( \w+ ) (
\s+ fish \b
)
/x) {
if (count += 1) == 4
'sushi' + $2
else
$1 + $2
end
}
pond = 'One fish two fish red fish blue fish swim here.'
puts "Last fish is #{pond.scan(/\b(\w+)\s+fish\b/i).flatten[-1]}"
/
A (?! .* A )
$ /x
pond = "One fish two fish red fish blue fish swim here."
if (pond =~ /
\b ( \w+) \s+ fish \b
(?! .* \b fish \b )
/mix)
puts "Last fish is #{$1}."
else
puts "Failed!"
end
$/ = nil; while file = gets() do
file.gsub!(/<.*?>/m,''); puts file end
$/ = ''
while file = gets() do
pattern = /
\A ( Chapter \s+ \d+ \s* : . * )
/x
puts file.gsub(pattern,'<H1>\1</H1>')
end
for file in ARGV
file = File.open(ARGV.shift)
while file.gets('') do print "chunk #{$.} in $ARGV has <<#{$1}>>\n" while /^START(.*?)^END/m
end end
$/ = nil;
file = File.open("datafile")
chunks = file.gets.split(/pattern/)
chunks = gets(nil).split(/^\.(Ch|Se|Ss)$/)
print "I read #{chunks.size} chunks.\n"
while gets
if ~/BEGIN/ .. ~/END/
end
end
while gets
if ($. == firstnum) .. ($. == lastnum)
end
end
while gets
if ~/BEGIN/ ... ~/END/
end
end
while gets
if ($. == first) ... ($. == last)
end
end
ruby -ne 'print if 15 .. 17' datafile
while gets
print if ~%rend
print if ~/begin/ .. ~/end/;
print if ~/begin/ ... ~/end/;
while gets
$in_header = $. == 1 .. ~/^$/ ? true : false
$in_body = ~/^$/ .. ARGF.eof ? true : false
end
seen = {}
ARGF.each do |line|
next unless line =~ /^From:?\s/i .. line =~ /^$/;
line.scan(%r/([^<>(),;\s]+\@[^<>(),;\s]+)/).each do |addr|
puts addr unless seen[addr]
seen[addr] ||= 1
end
end
def glob2pat(globstr)
patmap = {
'*' => '.*',
'?' => '.',
'[' => '[',
']' => ']',
}
globstr.gsub!(/(.)/) { |c| patmap[c] || Regexp::escape(c) }
'^' + globstr + '$'
end
pattern = ARGV.shift
ARGF.each do |line|
print line if line =~ /#{pattern}/
end
pattern = ARGV.shift
ARGF.each do |line|
print line if line =~ /#{pattern}/o
end
popstates = %w(CO ON MI WI MN)
ARGF.each do |line|
popstates.each do |state|
if line =~ /\b#{state}\b/
print line
last
end
end
end
popstates = %w(CO ON MI WI MN)
code = "ARGF.each do |line|\n"
popstates.each do |state|
code += "\tif line =~ /\\b#{state}\\b/; print(line); next; end\n"
end
code += "end\n"
print "CODE IS\n---\n#{code}\n---\n" if false eval code
popstates = %w(CO ON MI WI MN)
code = "ARGF.each do |line|\n case line\n"
popstates.each do |state|
code += " when /\\b#{state}\\b/ : print line\n"
end
code += " end\nend\n"
print "CODE IS\n---\n#{code}\n---\n" if false eval code
popstates = %w(CO ON MI WI MN)
expr = popstates.map{|e|"line =~ /\\b#{e}\\b/"}.join('||')
eval "def match_any(line); #{expr};end"
ARGF.each do |line|
print line if match_any(line)
end
class MultiMatch
def initialize(*patterns)
_any = build_match('||',patterns)
_all = build_match('&&',patterns)
eval "def match_any(line);#{_any};end\n"
eval "def match_all(line);#{_all};end\n"
end
def build_match(sym,args)
args.map{|e|"line =~ /#{e}/"}.join(sym)
end
end
mm = MultiMatch.new('foo','bar')
ARGF.each do |line|
print line if mm.match_all(line)
end
popstates = %w(CO ON MI WI MN)
popstates = popstates.map{|re| %r/\b#{re}\b/}
ARGF.each do |line|
popstates.each do |state_re|
if line =~ state_re
print line
break
end
end
end
begin
print "Pattern? "
pat = $stdin.gets.chomp
Regexp.new(pat)
rescue
warn "Invalid Pattern"
retry
end
require 'amatch'
matcher = Amatch.new('balast')
#$relative, $distance = 0, 1
File.open('/usr/share/dict/words').each_line do |line|
print line if matcher.search(line) <= 1
end
__END__
ballast
ballasts
balustrade
balustrades
blast
blasted
blaster
blasters
blasting
blasts
str.scan(/\G(\d)/).each do |token|
puts "found #{token}"
end
n = " 49 here"
n.gsub!(/\G /,'0')
puts n
str = "3,4,5,9,120"
str.scan(/\G,?(\d+)/).each do |num|
puts "Found number: #{num}"
end
require 'strscan'
text = 'the year 1752 lost 10 days on the 3rd of September'
sc = StringScanner.new(text)
while sc.scan(/.*?(\d+)/)
print "found: #{sc[1]}\n"
end
if sc.scan(/\S+/)
puts "Found #{sc[0]} after last number"
end
puts "The position in 'text' is: #{sc.pos}"
sc.pos = 30
puts "The position in 'text' is: #{sc.pos}"
str.gsub!(/<.*>/m,'')
str.gsub!(/<.*?>/m,'')
%r{ <b><i>(.*?)</i></b> }mx
%r/BEGIN((?:(?!BEGIN).)*)END/
%r{ <b><i>( (?: (?!</b>|</i>). )* ) </i></b> }mx
%r{ <b><i>( (?: (?!</[ib]>). )* ) </i></b> }mx
%r{
<b><i>
[^<]* (?:
(?! </?[ib]> ) < [^<]* ) *
</i></b>
}mx
$/ = ""
ARGF.each do |para|
para.scan %r/
\b (\S+) \b (
\s+ \1 \b ) + /xi do
puts "dup word '#{$1}' at paragraph #{$.}"
end
end
astr = 'nobody'
bstr = 'bodysnatcher'
if "#{astr} #{bstr}" =~ /^(\w+)(\w+) \2(\w+)$/
print "#{$2} overlaps in #{$1}-#{$2}-#{$3}"
end
ARGV << 180
cap = 'o' * ARGV.shift
while cap =~ /^(oo+?)\1+$/
print $1.size, " "
cap.gsub!(/#{$1}/,'o')
end
puts cap.size
if ('o' * 281).match(/^(o*)\1{11}(o*)\2{14}(o*)\3{15}$/)
x, y, z = $1.size, $2.size, $3.size
puts "One solution is: x=#{x}; y=#{y}; z=#{z}"
else
puts "No solution."
end
('o' * 281).match(/^(o+)\1{11}(o+)\2{14}(o+)\3{15}$/)
('o' * 281).match(/^(o*?)\1{11}(o*)\2{14}(o*)\3{15}$/)
('o' * 281).match(/^(o+?)\1{11}(o*)\2{14}(o*)\3{15}$/)
%r/alpha|beta/
%r/(?=.*alpha)(?=.*beta)/m
%r/alpha.*beta|beta.*alpha/m
%r/^(?:(?!beta).)*$/m
%r/(?=(?:(?!BAD).)*$)GOOD/m
if !(string =~ /pattern/) something()
end
if string !~ /pattern/ something()
end
if string =~ /pat1/ && string =~ /pat2/
something()
end
if string =~ /pat1/ || string =~ /pat2/
something()
end
pat = ARGV.shift
ARGF.each do |line|
print line if line =~ /#{pat}/o
end
"labelled" =~ /^(?=.*bell)(?=.*lab)/m
$string =~ /bell/ && $string =~ /lab/
$murray_hill = "blah bell blah "
if $murray_hill =~ %r{
^ (?= .* bell ) (?= .* lab )
}mx
print "Looks like Bell Labs might be in Murray Hill!\n";
end
"labelled" =~ /(?:^.*bell.*lab)|(?:^.*lab.*bell)/
$brand = "labelled";
if $brand =~ %r{
(?: ^ .*? bell .*? lab ) | (?: ^ .*? lab .*? bell ) }mx print "Our brand has bell and lab separate.\n";
end
$map =~ /^(?:(?!waldo).)*$/s
$map = "the great baldo"
if $map =~ %r{
^ (?: (?! waldo ) . ) * $ }mx print "There's no waldo here!\n";
end
7:15am up 206 days, 13:30, 4 users, load average: 1.04, 1.07, 1.04
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
tchrist tty1 5:16pm 36days 24:43 0.03s xinit
tchrist tty2 5:19pm 6days 0.43s 0.43s -tcsh
tchrist ttyp0 chthon 7:58am 3days 23.44s 0.44s -tcsh
gnat ttyS4 coprolith 2:01pm 13:36m 0.30s 0.30s -tcsh
%r{
^ (?! .* ttyp ) .* tchrist }x
ans = $stdin.gets.chomp
re = %r/^#{Regexp.quote(ans)}/
case
when "SEND" =~ re : puts "Action is send"
when "STOP" =~ re : puts "Action is stop"
when "ABORT" =~ re : puts "Action is abort"
when "EDIT" =~ re : puts "Action is edit"
end
require 'abbrev'
table = Abbrev.abbrev %w-send stop abort edit-
loop do
print "Action: "
ans = $stdin.gets.chomp
puts "Action for #{ans} is #{table[ans.downcase]}"
end
require 'abbrev'
file = 'pleac_ruby.data'
PAGER = 'less'
def invoke_editor
puts "invoking editor"
end
def deliver_message
puts "delivering message"
end
actions = {
'edit' => self.method(:invoke_editor),
'send' => self.method(:deliver_message),
'list' => proc {system(PAGER, file)},
'abort' => proc {puts "See ya!"; exit},
"" => proc {puts "Unknown Command"}
}
dtable = Abbrev.abbrev(actions.keys)
loop do
print "Action: "
ans = $stdin.gets.chomp.delete(" \t")
actions[ dtable[ans.downcase] || "" ].call
end
1 while addr.gsub!(/\([^()]*\)/,'')
Dear someuser@host.com,
Please confirm the mail address you gave us Wed May 6 09:38:41
MDT 1998 by replying to this message. Include the string
"Rumpelstiltskin" in that reply, but spelled in reverse; that is,
start with "Nik...". Once this is done, your confirmed address will
be entered into our records.
urls = '(https?|telnet|gopher|file|wais|ftp)';
ltrs = '\w';
gunk = '/#~:.?+=&%@!\-';
punc = '.:?\-';
any = "#{ltrs}#{gunk}#{punc}";
ARGF.each do |line|
line.gsub! %r/
\b ( #{urls} : [#{any}] +? ) (?= [#{punc}]* [^#{any}] | $ )
/iox do
%Q|<A HREF="#{$1}">#{$1}</A>|
end
print line
end
%r/^m*(d?c{0,3}|c[dm])(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])$/i
str.sub!(/(\S+)(\s+)(\S+)/, '\3\2\1')
%r/(\w+)\s*=\s*(.*)\s*$/ %r/.{80,}/
%r|(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+)|
str.gsub!(%r|/usr/bin|,'/usr/local/bin')
str.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/){ $1.hex.chr }
str.gsub!(%r{
/\* .*? \*/ }xm,'')
str.sub!(/^\s+/, '')
str.sub!(/\s+$/, '')
str.strip!
str.gsub!(/\\n/,"\n")
str.sub!(/^.*::/, '')
%r/^([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])\.
([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])$/x
str.sub!(%r|^.*/|, '')
cols = ( (ENV['TERMCAP'] || " ") =~ /:co#(\d+):/ ) ? $1 : 80;
name = " #{$0} #{ARGV}".gsub(%r| /\S+/|, ' ')
require 'rbconfig'
include Config
raise "This isn't Linux" unless CONFIG['target_os'] =~ /linux/i;
str.gsub!(%r/\n\s+/, ' ')
nums = str.scan(/(\d+\.?\d*|\.\d+)/)
capwords = str.scan(%r/(\b[^\Wa-z0-9_]+\b)/)
lowords = str.scan(%r/(\b[^\WA-Z0-9_]+\b)/)
icwords = str.scan(%r/(\b[^\Wa-z0-9_][^\WA-Z0-9_]*\b)/)
links = str.scan(%r/<A[^>]+?HREF\s*=\s*["']?([^'" >]+?)[ '"]?>/mi) #'
initial = str =~ /^\S+\s+(\S)\S*\s+\S/ ? $1 : ""
str.gsub!(%r/"([^"]*)"/, %q-``\1''-) #"
$/ = ""
sentences = []
ARGF.each do |para|
para.gsub!(/\n/, ' ')
para.gsub!(/ {3,}/,' ')
sentences << para.scan(/(\S.*?[!?.])(?= |\Z)/)
end
%r/(\d{4})-(\d\d)-(\d\d)/ %r/ ^
(?:
1 \s (?: \d\d\d \s)? | \(\d\d\d\) \s | (?: \+\d\d?\d? \s)? \d\d\d ([\s\-]) )
\d\d\d (\s|\1) \d\d\d\d $
/x
%r/\boh\s+my\s+gh?o(d(dess(es)?|s?)|odness|sh)\b/i
lines = []
lines << $1 while input.sub!(/^([^\012\015]*)(\012\015?|\015\012?)/,'')
File.open("/usr/local/widgets/data").each { |line|
puts line if line =~ /blue/
}
logfile = File.new("/var/log/rubylog.txt", "w")
mysub($stdin, logfile)
f = File.new("bla.txt")
begin
while (line = f.readline)
line.chomp
$stdout.print line if line =~ /blue/
end
rescue EOFError
f.close
end
while $stdin.gets unless (/\d/)
$stderr.puts "No digit found." end
puts "Read: #{$_}" end
logfile = File.new("/tmp/log", "w")
logfile.close
logfile = File.new("log.txt", "w")
old = $defout
$defout = logfile puts "Countdown initiated ..."
$defout = old puts "You have 30 seconds to reach minimum safety distance."
source = File.new(path, "r") sink = File.new(path, "w")
source = File.open(path, File::RDONLY) sink = File.open(path, File::WRONLY)
file = File.open(path, "r+") file = File.open(path, flags)
file = File.open(path, "r")
file = File.open(path, File::RDONLY)
file = File.open(path, "w")
file = File.open(path, File::WRONLY|File::TRUNC|File::CREAT)
file = File.open(path, File::WRONLY|File::TRUNC|File::CREAT, 0666)
file = File.open(path, File::WRONLY|File::EXCL|File::CREAT)
file = File.open(path, File::WRONLY|File::EXCL|File::CREAT, 0666)
file = File.open(path, "a")
file = File.open(path, File::WRONLY|File::APPEND|File::CREAT)
file = File.open(path, File::WRONLY|File::APPEND|File::CREAT, 0666)
file = File.open(path, File::WRONLY|File::APPEND)
file = File.open(path, "r+")
file = File.open(path, File::RDWR)
file = File.open(path, File::RDWR|File::CREAT)
file = File.open(path, File::RDWR|File::CREAT, 0600)
file = File.open(path, File::RDWR|File::EXCL|File::CREAT)
file = File.open(path, File::RDWR|File::EXCL|File::CREAT, 0600)
File.open(filename, 'r')
File.expand_path('~root/tmp')
File.expand_path('~rpcuser')
File.expand_path('~/tmp')
File.open('afile')
require 'tempfile'
tf = Tempfile.new('tmp')
tf.flush
system("/usr/bin/dowhatever #{tf.path}")
fh = Tempfile.new('tmp')
fh.sync = true 10.times { |i| fh.puts i }
fh.rewind
puts 'Tmp file has: ', fh.readlines
while (DATA.gets) do
end
__END__
kilosize = DATA.stat.size / 1024
last_modif = DATA.stat.mtime
puts "<P>Script size is #{kilosize}"
puts "<P>Last script update: #{last_modif}"
__END__
while line = gets do
end
while gets do
end
$stdin.each do |line|
end
ARGV.each do |filename|
open(filename) do |fd|
fd.each do |line|
end
end rescue abort("can't open %s" % filename)
end
ARGV = Dir["*.[Cch]"] if ARGV.empty?
if (ARGV[0] == '-c')
chop_first += 1
ARGV.shift
end
if ARGV[0] =~ /^-(\d+)$/
columns = $1
ARGV.shift
end
require 'optparse'
nostdout = 0
append = 0
unbuffer = 0
ignore_ints = 0
ARGV.options do |opt|
opt.on('-n') { nostdout +=1 }
opt.on('-a') { append +=1 }
opt.on('-u') { unbuffer +=1 }
opt.on('-i') { ignore_ints +=1 }
opt.parse!
end or abort("usage: " + __FILE__ + " [-ainu] [filenames]")
str = File.read(ARGV[0])
str = File.read(ARGV[0])
ARGF.each_with_index do |line, idx|
print ARGF.filename, ":", idx, ";", line
end
ARGF.each do |line|
puts line if line =~ /login/
end
ARGF.each { |l| puts l.downcase! }
$_.downcase!
chunks = 0
File.read(ARGV[0]).split.each do |word|
next if word =~ /^#/
break if ["__DATA__", "__END__"].member? word
chunks += 1
end
print "Found ", chunks, " chunks\n"
old = File.open(old_file)
new = File.open(new_file, "w")
while old.gets do
new.print $_
end
old.close
new.close
File.rename(old_file, "old.orig")
File.rename(new_file, old_file)
while old.gets do
if $. == 20 then new.puts "Extra line 1"
new.puts "Extra line 2"
end
new.print $_
end
while old.gets do
next if 20..30 new.print $_
end
ARGV << 'I'
oldfile = ""
while gets
if ARGF.filename != oldfile
newfile = ARGF.filename
File.rename(newfile, newfile + ".orig")
$stdout = File.open(newfile,'w')
oldfile = newfile
end
gsub!(/DATE/){Time.now}
print
end
$stdout = STDOUT
$-i = '.orig' ARGV.replace(Dir['*.[Cchy]'])
while gets
if $. == 1
print "This line should appear at the top of each file\n"
end
gsub!(/\b(p)earl\b/i, '\1erl') print
ARGF.close if ARGF.eof
end
File.open('itest', 'r+') do |f| lines = f.readlines lines.each do |it| it.gsub!(/foo/, 'QQQ')
end
f.pos = 0 f.print lines f.truncate(f.pos) end File.open('itest', 'r+') do |f|
out = ""
f.each do |line|
out << line.gsub(/DATE/) {Time.now}
end
f.pos = 0
f.print out
f.truncate(f.pos)
end
File.open('infile', 'r+') do |f|
f.flock File::LOCK_EX
end
File::LOCK_SH File::LOCK_EX File::LOCK_NB File::LOCK_UN unless f.flock File::LOCK_EX | File::LOCK_NB
warn "can't get immediate lock: blocking ..."
f.flock File::LOCK_EX
end
File.open('numfile', File::RDWR|File::CREAT) do |f|
f.flock(File::LOCK_EX)
num = f.gets.to_i || 0
f.pos = 0
f.truncate 0
f.puts num + 1q
end
output_handle.sync = true
$stdout.sync = ARGV.size > 0
print "Now you don't see it..."
sleep 2
puts "now you do"
$stderr.sync = true
afile.sync = false
remote_con.sync = true disk_file.sync = false require 'socket'
sock = TCPSocket.new('www.ruby-lang.org', 80)
sock.sync = true
sock.puts "GET /en/ HTTP/1.0 \n\n"
resp = sock.read
print "DOC IS: #{resp}\n"
nfound = select([$stdin, fh1, fh2, fh3], nil, nil, 0)
nfound[0].each do |file|
case file
when fh1
when fh2
when fh3
end
end
input_files = []
input_files << fh1
if nfound = select(input_files, nil, nil, 0)
end
begin
File.open fname, (File::RDONLY | File::NONBLOCK) do |io|
puts io.sysread(4096) end
rescue EOFError
rescue IOError => e
puts e.exception
rescue Errno::ENOENT
puts "no such file #{fname}"
end
begin
File.open fname, (File::RDONLY | File::NONBLOCK) do |io|
puts io.read(4096) end
rescue Errno::ENOENT
puts "no such file #{fname}"
end
def subroutine(fh):
fh.print "Hello, file"
end
variable = fh
subroutine(variable)
filehandles.each do |filehandle|
filehandle.print stuff_to_print
end
IO.popen("tee file1 file2 file3 >/dev/null", "w") do |many|
many.puts "data"
end
[fh1 fh2 fh3].each {|fh| fh.puts "whatever" }
$stdout = IO.popen("tee file1 file2 file3", "w")
puts "whatever"
$stdout.close
$stdout = STDOUT class MultiDispatcher < BasicObject def initialize(targets)
@targets = targets
end
def method_missing(*a,&b)
@targets.each {|tgt| tgt.send(*a,&b)}
end
end
md = MultiDispatcher.new [$stdout, $stderr]
4.times {|i| md.printf "%3d\n", i}
md.close
datafile.readlines.each { |line|
line.chomp!
size = line.length
puts size
}
datafile.readlines.each { |line|
puts line.chomp!.length
}
lines = datafile.readlines
whole_file = file.read
#{word}handle.print "one", "two", "three" puts "Baa baa black sheep." buffer = handle.read(4096)
rv = buffer.length
handle.truncate(length)
open("/tmp#{$$}.pid", 'w') { |handle| handle.truncate(length) }
pos = datafile.pos puts "I'm #{pos} bytes from the start of datafile"
logfile.seek(0, IO::SEEK_END)
datafile.seek(pos) out.seek(-20, IO::SEEK_CUR)
written = datafile.syswrite(mystring)
raise RunTimeError unless written == mystring.length
block = infile.sysread(256) puts "only read #{block.length} bytes" if 256 != block.length
pos = handle.sysseek(0, IO::SEEK_CUR)
while (line = fh.gets)
line.chomp!
nextline = nil
line.gsub!(/\\$/) { |match| nextline = fh.gets; '' }
if (nextline != nil)
line += nextline
redo
end
end
line.gsub!(/\\\s*$/, '') {
}
count = `wc -l < #{filename}`
fail "wc failed: #{$?}" if $? != 0
count.chomp!
count = 0
File.open(file, 'r') { |fh|
count += 1 while fh.gets
}
count = 0
while (chunk = file.sysread(2**16))
count += chunk.count("\n")
end rescue EOFError
File.open(filename,'r') { |fh|
count += 1 while fh.gets
}
count = File.readlines(filename).size
1 while file.gets
count = $.
$/ = ''
open(filename, 'r') { |fh|
1 while fh.gets
para_count = $.
} rescue fail("can't open #{filename}: $!")
while (gets)
split.each { |chunk|
}
end
while (gets)
gsub(/(\w[\w'-]*)/) { |word|
}
end
seen = Hash.new(0)
while (gets)
gsub(/(\w[\w'-]*)/) { |word|
seen[word.downcase] += 1
}
end
seen.sort { |a,b| b[1] <=> a[1] }.each do |k,v|
printf("%5d %s\n", v, k )
end
seen = Hash.new(0)
while (gets)
seen[$_.downcase] += 1
end
seen.sort { |a,b| b[1] <=> a[1] }.each do |k,v|
printf("%5d %s\n", v, k )
end
File.readlines(file).each { |line|
}
File.readlines(file).reverse_each { |line|
}
(lines.size - 1).downto(0) { |i|
line = lines[i]
}
File.readlines(file, '').each { |paragraph|
puts "->Paragraph #{paragraph}"
}
file = File.open('growing.txt') while File.exists?(file.path) puts file.gets while !file.eof? sleep(1) end
filename = 'growing.txt'
file = File.open(filename)
while File.exists?(file.path)
if File.size(filename) < file.pos
puts "File truncated - reopening."
file = File.open(filename)
end
puts file.gets while !file.eof?
sleep(1)
end
$/ = "%\n"
srand
File.open('/usr/share/fortune/humorists').each do |line|
adage = line if rand($.) < 1
end
puts adage
def fisher_yates_shuffle(a)
(a.size-1).downto(1) { |i|
j = rand(i+1)
a[i], a[j] = a[j], a[i] if i != j
}
end
lines = File.open('to_randomize.txt').collect
fisher_yates_shuffle(lines)
puts lines
begin
fh = File.open(file, "r+")
addr = fh.tell unless fh.eof while fh.gets
fh.truncate(addr)
rescue SystemCallError
$stderr.puts "#$!"
end
entry = File.stat("/usr/bin/vi")
entry = File.stat("/usr/bin")
entry = File.stat(INFILE)
entry = File.stat("/usr/bin/vi")
ctime = entry.ctime
size = entry.size
f = File.open(filename, "r")
if test(?s, filename)
puts "#{filename} doesn't have text in it."
exit
end
Dir.new("/usr/bin").each do |filename|
puts "Inside /usr/bin is something called #{filename}"
end
file = File.stat("filename")
readtime, writetime = file.atime, file.mtime
file.utime(readtime, writetime)
SECONDS_PER_DAY = 60 * 60 * 24
file = File.stat("filename")
atime, mtime = file.atime, file.mtime
atime -= 7 * SECONDS_PER_DAY
mtime -= 7 * SECONDS_PER_DAY
File.utime(atime, mtime, file)
mtime = File.stat(file).mtime
File.utime(Time.new, mtime, file)
File.utime(Time.new, File.stat("testfile").mtime, file)
if ARGV.length != 1
puts "usage: uvi filename"
exit
end
file = ARGV[0]
atime, mtime = File.stat(file).atime, File.stat(file).mtime
system(ENV["EDITOR"] || "vi", file)
File.utime(atime, mtime, file)
File.unlink(FILENAME)
err_flg = false
filenames.each do |file|
begin
File.unlink(file)
rescue
err_flg = $!
end
end
err_flg and raise "Couldn't unlink all of #{filenames.join(" ")}: #{err_flg}"
File.unlink(file)
count = filenames.length
filenames.each do |file|
begin
File.unlink(file)
rescue
count -= 1
end
end
if count != filenames.length
STDERR.puts "could only delete #{count} of #{filenames.length} files"
end
require "ftools"
File.copy(oldfile, newfile)
infile = File.open(oldfile, "r")
outfile = File.open(newfile, "w")
blksize = infile.stat.blksize
while (line = infile.read(blksize))
outfile.write(line)
end
infile.close
outfile.close
system("cp #{oldfile} #{newfile}") system("copy #{oldfile} #{newfile}")
require "ftools"
File.copy("datafile.dat", "datafile.bak")
File.move("datafile.new", "datafile.dat")
$seen = {}
def do_my_thing(filename)
dev, ino = File.stat(filename).dev, File.stat(filename).ino
unless $seen[[dev, ino]]
end
$seen[[dev, ino]] = $seen[[dev, ino]].to_i + 1
end
files.each do |filename|
dev, ino = File.stat(filename).dev, File.stat(filename).ino
if !$seen.has_key?([dev, ino])
$seen[[dev, ino]] = []
end
$seen[[dev, ino]].push(filename)
end
$seen.keys.sort.each do |devino|
ino, dev = devino
if $seen[devino].length > 1
end
end
Dir.open(dirname) do |dir|
dir.each do |file|
puts file
end
end
dir.each do |file|
next if file =~ /^\.\.?$/
end
def plainfiles(dir)
dh = Dir.open(dir)
dh.entries.grep(/^[^.]/).
map {|file| "#{dir}/#{file}"}.
find_all {|file| test(?f, file)}.
sort
end
list = Dir.glob("*.c")
dir = Dir.open(path)
files = dir.entries.grep(/\.c$/)
dir.close
files = Dir.glob("*.c")
files = Dir.open(path).entries.grep(/\.[ch]$/i)
dir = Dir.new(path)
files = dir.entries.grep(/\.[ch]$/i)
begin
d = Dir.open(dir)
rescue Errno::ENOENT
raise "Couldn't open #{dir} for reading: #{$!}"
end
files = []
d.each do |file|
puts file
next unless file =~ /\.[ch]$/i
filename = "#{dir}/#{file}"
files.push(filename) if test(?s, filename)
end
dirs.entries.grep(/^\d+$/).
map { |file| [file, "#{path}/#{file}"]} .
select { |file| test(?d, file[1]) }.
sort { |a,b| a[0] <=> b[0] }.
map { |file| file[1] }
require 'find'
Find.find(dirlist) do |file|
end
require 'find'
argv = ARGV.empty? ? %w{.} : ARGV
Find.find(*argv) do |file|
print file, (test(?d, file) ? "/\n" : "\n")
end
require 'find'
argv = ARGV.empty? ? %w{.} : ARGV
sum = 0
Find.find(*argv) do |file|
size = test(?s, file) || 0
sum += size
end
puts "#{argv.join(' ')} contains #{sum} bytes"
require 'find'
argv = ARGV.empty? ? %w{.} : ARGV
saved_size, saved_name = -1, ""
Find.find(*argv) do |file|
size = test(?s, file) || 0
next unless test(?f, file) && size > saved_size
saved_size = size
saved_name = file
end
puts "Biggest file #{saved_name} in #{argv.join(' ')} is #{saved_size}"
require 'find'
argv = ARGV.empty? ? %w{.} : ARGV
age, name = nil
Find.find(*argv) do |file|
mtime = File.stat(file).mtime
next if age && age > mtime
age = mtime
name = file
end
puts "#{name} #{age}"
require 'find'
argv = ARGV.empty? ? %w{.} : ARGV
File.find(*argv) { |file| puts file if test(?d, file) }
require 'fileutils'
puts "Usage #{$0} dir ..." if ARGV.empty?
ARGV.each do |dir|
FileUtils.rmtree(dir)
end
require 'ftools'
names.each do |file|
newname = file
begin
File.move(file, newname)
rescue Errno::EPERM
$stderr.puts "Couldn't rename #{file} to #{newname}: #{$!}"
end
end
require 'ftools'
op = ARGV.empty? ? (raise "Usage: rename expr [files]\n") : ARGV.shift
argv = ARGV.empty? ? $stdin.readlines.map { |f| f.chomp } : ARGV
argv.each do |file|
was = file
file = eval("file.#{op}")
File.move(was, file) unless was == file
end
base = File.basename(path)
dir = File.dirname(path)
dir, base = File.split(path)
ext = base.scan(/\..*$/).to_s
path = '/usr/lib/libc.a'
file = File.basename(path)
dir = File.dirname(path)
puts "dir is #{dir}, file is #{file}"
path = '/usr/lib/libc.a'
dir, filename = File.split(path)
name, ext = filename.split(/(?=\.)/)
puts "dir is #{dir}, name is #{name}, ext is #{ext}"
def extension(path)
ext = path.scan(/\..*$/).to_s
ext.sub(/^\./, "")
end
require 'find'
require 'fileutils'
raise "usage: #{$0} realdir mirrordir" unless ARGV.size == 2
srcdir,dstdir = ARGV
srcmode = File::stat(srcdir).mode
Dir.mkdir(dstdir, srcmode & 07777) unless test(?d, dstdir)
Dir.chdir(srcdir) {srcdir = Dir.pwd}
Dir.chdir(dstdir) {dstdir = Dir.pwd}
Find.find(srcdir) do |srcfile|
if test(?d, srcfile)
dest = srcfile.sub(/^#{srcdir}/, dstdir)
dmode = File::stat(srcfile).mode & 07777
Dir.mkdir(dest, dmode) unless test(?d, dest)
a = Dir["#{srcfile}/*"].reject{|f| test(?d, f)}
FileUtils.ln_s(a, dest)
end
end
require 'find'
require 'etc'
require "Getopt/Declare"
opts = Getopt::Declare.new(<<'EOPARAM')
============
Input Format:
-i read from stdin
============
Output Format:
-l long listing
-r reverse listing
============
Sort on: (one of)
-m mtime (modify time - default)
{$sort_criteria = :mtime}
-u atime (access time)
{$sort_criteria = :atime}
-c ctime (inode change time)
{$sort_criteria = :ctime}
-s size
{$sort_criteria = :size}
[mutex: -m -u -c -s]
EOPARAM
$sort_criteria ||= :mtime
files = {}
DIRS = opts['-i'] ? $stdin.readlines.map{|f|f.chomp!} : ARGV
DIRS.each do |dir|
Find.find(dir) do |ent|
files[ent] = File::stat(ent)
end
end
entries = files.keys.sort_by{|f| files[f].send($sort_criteria)}
entries = entries.reverse unless opts['-r']
entries.each do |ent|
unless opts['-l']
puts ent
next
end
stats = files[ent]
ftime = stats.send($sort_criteria == :size ? :mtime : $sort_criteria)
printf "%6d %04o %6d %8s %8s %8d %s %s\n",
stats.ino,
stats.mode & 07777,
stats.nlink,
ETC::PASSWD[stats.uid].name,
ETC::GROUP[stats.gid].name,
stats.size,
ftime.strftime("%a %b %d %H:%M:%S %Y"),
ent
end
def hello
$greeted += 1 puts "hi there!"
end
$greeted = 0
hello
def hypotenuse(side1, side2)
Math.sqrt(side1**2 + side2**2) end
diag = hypotenuse(3, 4)
puts hypotenuse(3, 4)
a = [3, 4]
print hypotenuse(*a)
both = men + women
nums = [1.4, 3.5, 6.7]
def int_all(n)
n.collect { |v| v.to_i }
end
ints = int_all(nums)
nums = [1.4, 3.5, 6.7]
def trunc_em(n)
n.collect! { |v| v.to_i } end
trunc_em(nums)
def somefunc
variable = something end
name, age = ARGV
start = fetch_time
a, b = pair c = fetch_time
def check_x(x)
y = "whatever"
run_check
if $condition
puts "got $x"
end
end
def save_array(ary)
$global_array << ary
end
def save_array(ary)
$global_array += ary
end
BEGIN { puts "hello from BEGIN" }
puts "hello from main"
BEGIN { puts "hello from 2nd BEGIN" }
class Counter
@@counter = 0
def Counter.next_counter; @@counter += 1; end
end
class Counter
@@counter = 42
def Counter.next_counter; @@counter += 1; end
def Counter.prev_counter; @@counter -= 1; end
end
caller
caller[0]
def whoami; caller()[0] =~ /in `([^']+)'/ ? $1 : '(anonymous)'; end
def whowasi; caller()[1] =~ /in `([^']+)'/ ? $1 : '(anonymous)'; end
array_diff(array1, array2)
def add_vecpair(a1, a2)
results = []
a1.each_index { |i| results << (a1[i] + a2[i]) }
results
end
a = [1, 2]
b = [5, 8]
c = add_vecpair(a, b)
p c
a1.type == Array && a2.type == Array or
raise "usage: add_vecpair array1 array2 (was used with: #{a1.type} #{a2.type})"
def thefunc(param_args)
args = { 'INCREMENT' => '10s', 'FINISH' => '0', 'START' => 0 }
args.update(param_args)
if (args['INCREMENT'] =~ /m$/ )
end
end
thefunc({ 'INCREMENT' => '20s', 'START' => '+5m', 'FINISH' => '+30m' })
thefunc({})
a, c = func.indexes(0, 2)
def somefunc
ary = []
hash = {}
return ary, hash
end
arr, dict = somefunc
array_of_hashes = fn
h1, h2, h3 = fn
return
return nil
def func_with_no_arg; end
def func_with_no_arg(); end
def func_with_one_arg(a1); end
def func_with_two_args(a1, a2); end
def func_with_any_number_of_args(*args); end
raise "some message"
begin
val = func
rescue Exception => msg
$stderr.puts "func raised an exception: #{msg}"
end
begin
val = func
rescue FullMoonError
...
end
def print_age
puts "Age is #{$age}"
end
$age = 18 print_age()
if condition
safeage = $age
$age = 23
print_age()
$age = safeage
end
def local(var)
eval("save = #{var.id2name}")
begin
result = yield
ensure
eval("#{var.id2name} = save")
end
result
end
condition = true
$age = 18
print_age()
if condition
local(:$age) {
$age = 23
print_age()
}
end
print_age()
def foo; puts 'foo'; end
def foo; puts 'bar'; end
foo
def foo; puts 'foo'; end
alias foo_orig foo
def foo; puts 'bar'; end
foo_orig
foo
colors = %w(red blue green yellow orange purple violet)
colors.each { |c|
eval <<-EOS
def #{c}(*a)
"<FONT COLOR='#{c}'>" + a.to_s + "</FONT>"
end
EOS
}
def method_missing(name, *args)
"<FONT COLOR='#{name}'>" + args.join(' ') + "</FONT>"
end
puts chartreuse("stuff")
def outer(arg)
x = arg + 35
inner = proc { x * 19 }
x + inner.call()
end
require 'English'
require 'Date'
class Mail
attr_accessor :no
attr_accessor :subject
attr_accessor :fulltext
attr_accessor :date
def initialize
@fulltext = ""
@subject = ""
end
def append(para)
@fulltext << para
end
def to_s
@fulltext
end
end
class Mailbox < Array
Subjectpattern = Regexp.new('Subject:\s*(?:Re:\s*)*(.*)\n')
Datepattern = Regexp.new('Date:\s*(.*)\n')
def read(file)
$INPUT_RECORD_SEPARATOR = '' msgno = -1
file.each { |para|
if para =~ /^From/
mail = Mail.new
mail.no = (msgno += 1)
md = Subjectpattern.match(para)
if md
mail.subject = md[1]
end
md = Datepattern.match(para)
if md
mail.date = DateTime.parse(md[1])
else
mail.date = DateTime.now
end
self.push(mail)
end
mail.append(para) if mail
}
end
def sort_by_subject_and_no
self.sort_by { |m|
[m.subject, m.no]
}
end
def sort_by_attributs(*attrs)
self.sort_by { |elem|
attrs.map { |attr|
elem.send(attr)
}
}
end
end
mailbox = Mailbox.new
mailbox.read(ARGF)
for m in mailbox.sort_by_subject_and_no
puts(m.subject)
end
for m in mailbox.sort_by_attributs(:date, :subject)
puts(m)
end
hash["KEYNAME"] << "new value"
hash.each { |key, value|
puts "#{key}: #{value.join(', ')}"
}
hash["a key"] = [3, 4, 5]
values = hash["a key"]
hash["a key"] << value
residents = phone2name[number]
residents = phone2name.has_key?(number) ? phone2name[number] : []
record = {
:NAME => "Jason",
:EMPNO => 132,
:TITLE => "deputy peon",
:AGE => 23,
:SALARY => 37.000,
:PALS => [ "Norbert", "Rhys", "Phineas"]
}
puts "I am #{record[:NAME]}, and my pals are #{record[:PALS].join(', ')}."
byname = {}
byname[record[:NAME]] = record
rp = byname["Aron"]
puts "Aron is employee #{rp[:EMPNO]}." if rp
byname["Jason"][:PALS] << "Theodore"
puts "Jason now has #{byname["Jason"][:PALS].length} pals"
byname.each do |name, record|
puts "#{name} is employee number #{record[:EMPNO]}"
end
employees = {}
employees[record[:EMPNO]] = record
rp = employees[132]
puts "employee number 132 is #{rp[:NAME]}" if rp
byname["Jason"][:SALARY] *= 1.035
peons = employees.values.select { |record| record[:TITLE] =~ /peon/i }
tsevens = employees.values.select { |record| record[:AGE] == 27 }
byname.values.sort { |a, b| a[:AGE] <=> b[:AGE] }.each do |rp|
puts "#{rp[:NAME]} is age #{rp[:AGE]}."
end
byage = {}
byage[record[:AGE]] = [] if byage[record[:AGE]] == nil
byage[record[:AGE]] << record
byage.each do |age, rps|
print "Age #{age}: "
rps.each do |rp|
print rp[:NAME], " "
end
print "\n"
end
byage.each do |age, rps|
puts "Age #{age}: #{byage[age].collect { |e| e[:NAME] }.join(', ')}"
end
def mkcounter(count)
start = count
bundle = {
"NEXT" => proc { count += 1 },
"PREV" => proc { count -= 1 },
"RESET" => proc { count = start }
}
bundle["LAST"] = bundle["PREV"]
return bundle
end
c1 = mkcounter(20)
c2 = mkcounter(77)
puts "next c1: #{c1["NEXT"].call}" puts "next c2: #{c2["NEXT"].call}" puts "next c1: #{c1["NEXT"].call}" puts "last c1: #{c1["PREV"].call}" puts "last c1: #{c1["LAST"].call}" puts "old c2: #{c2["RESET"].call}"
class Binary_tree
def initialize(val)
@value = val
@left = nil
@right = nil
end
def insert(val)
if val < @value then
if @left then
@left.insert(val)
else
@left = Binary_tree.new(val)
end
elsif val > @value then
if @right then
@right.insert(val)
else
@right = Binary_tree.new(val)
end
else
puts "double"
end
end
def in_order
@left.in_order if @left
print @value, " "
@right.in_order if @right
end
def pre_order
print @value, " "
@left.pre_order if @left
@right.pre_order if @right
end
def post_order
@left.post_order if @left
@right.post_order if @right
print @value, " "
end
def search(val)
if val == @value then
return self
elsif val < @value then
return @left.search(val) if @left
return nil
else
return @right.search(val) if @right
return nil
end
end
end
test = Binary_tree.new(0)
for a in 0..20
test.insert(rand(1000))
end
print "Pre order: "; test.pre_order; puts ""
print "In order: "; test.in_order; puts ""
print "Post order: "; test.post_order; puts ""
print "search?"
while gets
print test.search($_.to_i)
print "\nsearch?"
end
module Alpha
NAME = 'first'
end
module Omega
NAME = 'last'
end
puts "Alpha is #{Alpha::NAME}, Omega is #{Omega::NAME}"
require 'getoptlong.rb'
require 'getoptlong' require 'cards/poker.rb'
require 'cards/poker' load 'cards/poker'
module Cards
module Poker
@card_deck = Array.new def shuffle
end
end
end
module Your_Module
def self.function
end
def Your_Module.another
end
end
begin
require 'nonexistent'
rescue LoadError
puts "Couldn't load #{$!}" end
module Alpha
@aa = 10
@bb = 11
def self.put_aa
puts @aa
end
def self.bb=(val)
@bb = val
end
end
Alpha.bb = 12
module MyModule
def find_caller
caller
end
def find_caller2(i)
caller(i) end
end
BEGIN {
$logfile = '/tmp/mylog' unless defined? $logfile
$LF = File.open($logfile, 'a')
}
module Logger
def self.logmsg(msg)
$LF.puts msg
end
logmsg('startup')
end
END {
Logger::logmsg('shutdown')
$LF.close
}
#$ export RUBYLIB=$HOME/rubylib
$LOAD_PATH.unshift "/projects/spectre/lib";
module FineTime
def self.time
end
end
module FineTime
def self.time
"its a fine time"
end
end
puts FineTime.time
def even_only(n)
raise "#{n} is not even" if (n & 1) != 0 end
def even_only(n)
$stderr.puts "#{n} is not even" if (n & 1) != 0
end
class Person
@@person_counter=0
def initialize(age, name, alive = true) @age, @name, @alive = age, name, alive @@person_counter += 1
end
attr_accessor :name, :age
def die!
@alive = false
puts "#{@name} has died at the age of #{@age}."
@alive
end
def kill(anotherPerson)
print @name, ' is killing ', anotherPerson.name, ".\n"
anotherPerson.die!
end
def alive?
@alive && true
end
def year_of_birth
Time.now.year - @age
end
def Person.number_of_people
@@person_counter
end
end
lecter = Person.new(47, 'Hannibal')
starling = Person.new(29, 'Clarice', true)
pazzi = Person.new(40, 'Rinaldo', true)
print "There are ", Person.number_of_people, " Person objects\n"
print pazzi.name, ' is ', (pazzi.alive?) ? 'alive' : 'dead', ".\n"
lecter.kill(pazzi)
print pazzi.name, ' is ', (pazzi.alive?) ? 'alive' : 'dead', ".\n"
print starling.name , ' was born in ', starling.year_of_birth, "\n"
class MyClass
end
class MyClass
def initialize
@start = Time.new
@age = 0
end
end
class MyClass
def initialize(inithash)
@start = Time.new
@age = 0
for key, value in inithash
instance_variable_set("@#{key}", value)
end
end
end
class MyClass
def initialize
ObjectSpace.define_finalizer(self,
self.class.method(:finalize).to_proc)
end
def MyClass.finalize(id)
puts "Object #{id} dying at #{Time.new}"
end
end
3.times {
MyClass.new
}
ObjectSpace.garbage_collect
class Person
def name
@name
end
def name=(name)
@name = name
end
end
class Person
attr_reader :age
attr_writer :name
end
class Person
attr_accessor :age, :name
end
class Person
@@person_counter = 0
def Person.population
@@person_counter
end
def initialize
@@person_counter += 1
ObjectSpace.define_finalizer(self,
self.class.method(:finalize).to_proc)
end
def Person.finalize(id)
@@person_counter -= 1
end
end
people = []
10.times {
people.push(Person.new)
}
printf("There are %d people alive", Person.population)
FixedArray.class_max_bounds = 100
alpha = FixedArray.new
puts "Bound on alpha is #{alpha.max_bounds}"
beta = FixedArray.new
beta.max_bounds = 50 beta.class.class_max_bounds = 50 puts "Bound on alpha is #{alpha.max_bounds}"
class FixedArray
@@bounds = 7
def max_bounds
@@max_bounds
end
def max_bounds=(value)
@@max_bounds = value
end
def FixedArray.class_max_bounds=(value)
@@max_bounds = value
end
end
PersonStruct = Struct.new("Person", :name, :age, :peers)
p = PersonStruct.new
p = Struct::Person.new p.name = "Jason Smythe"
p.age = 13
p.peers = ["Wilbur", "Ralph", "Fred"]
p[:peers] = ["Wilbur", "Ralph", "Fred"] p["peers"] = ["Wilbur", "Ralph", "Fred"] p[2] = ["Wilbur", "Ralph", "Fred"] puts "At age #{p.age}, #{p.name}'s first friend is #{p.peers[0]}"
FamilyStruct = Struct.new("Family", :head, :address, :members)
folks = FamilyStruct.new
folks.head = PersonStruct.new
dad = folks.head
dad.name = "John"
dad.age = 34
class PersonStruct
def age=(value)
if !value.kind_of?(Integer)
raise(ArgumentError, "Age #{value} isn't an Integer")
elsif value > 150
raise(ArgumentError, "Age #{value} is unreasonable")
end
@age = value
end
end
class A
def new
dup
end
end
ob1 = A.new
ob2 = ob1.new
methname = 'flicker'
obj.send(methname, 10)
['start', 'run', 'stop'].each do |method_string|
obj.send(method_string)
end
method_obj = obj.method('flicker')
method_obj.call(10)
puts any_object.type
puts any_object.class.superclass
n = 4.7
puts n.instance_of?(Float) puts n.instance_of?(Numeric)
puts n.kind_of?(Float) puts n.kind_of?(Numeric) puts n.kind_of?(Comparable) puts n.kind_of?(String)
puts n.respond_to?('+') puts n.respond_to?('length')
'just a string'.methods.each { |m| puts m }
class Person
attr_accessor :age, :name
def initialize
@name
@age
end
end
dude = Person.new
dude.name = 'Jason'
dude.age = 23
printf "%s is age %d.\n", dude.name, dude.age
class Employee < Person
attr_accessor :salary
end
empl = Employee.new
empl.name = 'Jason'
empl.age = 23
empl.salary = 200
printf "%s is age %d, the salary is %d.\n", empl.name, empl.age, empl.salary
class WeirdString < String
def initialize(obj)
super obj
end
def +(anotherObj) self.length + anotherObj.length end
end
a = WeirdString.new('hello')
b = WeirdString.new('bye')
puts a + b puts a.length
class Person
def initialize
@ok_fields = %w(name age peers parent)
end
def valid_attribute?(name)
@ok_fields.include?(name)
end
def method_missing(namesymbol, *params)
name = namesymbol.to_s
return if name =~ /^A-Z/
if name.to_s[-1] == ('='[0]) isSetter = true
name.sub!(/=$/, '')
end
if valid_attribute?(name)
if isSetter
instance_variable_set("@#{name}", *params)
else
instance_variable_get("@#{name}", *params)
end
else
super(namesymbol, *params)
end
end
def new
kid = Person.new
kid.parent = self
kid
end
end
dad = Person.new
dad.name = "Jason"
dad.age = 23
kid = dad.new
kid.name = "Rachel"
kid.age = 2
puts "Kid's parent is #{kid.parent.name}"
puts dad
puts kid
class Employee < Person
def initialize
super
@ok_fields.push("salary", "boss")
end
def ok_fields
@ok_fields
end
end
class RingNode
attr_accessor :next
attr_accessor :prev
attr_reader :name
def initialize(aName)
@name = aName
ObjectSpace.define_finalizer(self,
self.class.method(:finalize).to_proc)
end
def RingNode.finalize(id)
puts "Node #{id} dying"
end
def RingNode.show_all_objects
ObjectSpace.each_object {|id|
puts id.name if id.class == RingNode
}
end
end
def create_test
a = RingNode.new("Node A")
b = RingNode.new("Node B")
c = RingNode.new("Node C")
a.next = b
b.next = c
c.next = a
a.prev = c
c.prev = b
b.prev = a
a = nil
b = nil
c = nil
end
create_test
RingNode.show_all_objects
ObjectSpace.garbage_collect
puts "After garbage collection"
RingNode.show_all_objects
class String
def <=>(other)
self.casecmp other
end
end
class TimeNumber
attr_accessor :hours,:minutes,:seconds
def initialize( hours, minutes, seconds)
@hours = hours
@minutes = minutes
@seconds = seconds
end
def to_s
return sprintf( "%d:%02d:%02d", @hours, @minutes, @seconds)
end
def to_str
to_s
end
def +( other)
seconds = @seconds + other.seconds
minutes = @minutes + other.minutes
hours = @hours + other.hours
if seconds >= 60
seconds %= 60
minutes += 1
end
if minutes >= 60
minutes %= 60
hours += 1
end
return TimeNumber.new(hours, minutes, seconds)
end
def -(other)
raise NotImplementedError
end
def *(other)
raise NotImplementedError
end
def /( other)
raise NotImplementedError
end
end
t1 = TimeNumber.new(0, 58, 59)
sec = TimeNumber.new(0, 0, 1)
min = TimeNumber.new(0, 1, 0)
puts t1 + sec + min + min
x = "Red"; y = "Black"
z = x+y
r = z*3 puts "values are #{x}, #{y}, #{z}, and #{r}"
print "#{x} is ", x < y ? "LT" : "GE", " #{y}\n"
class FixNum
REGEX = /(\.\d*)/
DEFAULT_PLACES = 0
attr_accessor :value, :places
def initialize(value, places = nil)
@value = value
if places
@places = places
else
m = REGEX.match(value.to_s)
if m
@places = m[0].length - 1
else
@places = DEFAULT_PLACES
end
end
end
def +(other)
FixNum.new(@value + other.value, max(@places, other.places))
end
def *(other)
FixNum.new(@value * other.value, max(@places, other.places))
end
def /(other)
puts "Divide: #{@value.to_f/other.value.to_f}"
result = FixNum.new(@value.to_f/other.value.to_f)
result.places = max(result.places,other.places)
result
end
def to_s
sprintf("STR%s: %.*f", self.class.to_s , @places, @value) end
def to_str
to_s
end
def to_i @value.to_i
end
def to_f @value.to_f
end
private
def max(a,b)
a > b ? a : b
end
end
def demo()
x = FixNum.new(40)
y = FixNum.new(12, 0)
puts "sum of #{x} and #{y} is #{x+y}"
puts "product of #{x} and #{y} is #{x*y}"
z = x/y
puts "#{z} has #{z.places} places"
unless z.places
z.places = 2
end
puts "div of #{x} by #{y} is #{z}"
puts "square of that is #{z*z}"
end
if __FILE__ == $0
demo()
end
require "sdbm"
SDBM.open("filename", 0666) { |dbobj|
v = dbobj["key"]
dbobj["key"] = "newvalue"
if dbobj.has_key?("key")
end
dbobj.delete("key2")
}
dbobj = SDBM.open("filename", 0666)
dbobj.close
require "sdbm"
filename = '/tmp/userstats.db'
SDBM.open(filename, 0666) { |dbobj|
if ARGV.length > 0
if ARGV[0] == "ALL"
userlist = dbobj.keys().sort()
else
userlist = ARGV
end
userlist.each { |user|
print "#{user}\t#{dbobj[user]}\n"
}
else
who = `who`
who.split("\n").each { |line|
md = /^(\S+)/.match(line)
raise "Bad line from who: #{line}" unless md
if dbobj.has_key?(md[0])
dbobj[md[0]] = dbobj[md[0]].to_i + 1
else
dbobj[md[0]] = "1"
end
}
end
}
dbobj = SDBM.open("filename", 0666)
dbobj.clear()
dbobj.close()
begin
File.delete("filename")
dbobj = SDBM.open("filename", 0666)
rescue
end
require "sdbm"
require "gdbm"
unless ARGV.length == 2
fail "usage: sdbm2gdbm infile outfile"
end
infile = ARGV[0]
outfile = ARGV[1]
sdb = SDBM.open(infile)
gdb = GDBM.open(outfile, 0666)
sdb.each { |key, val|
gdb[key] = val
}
gdb.close
sdb.close
require "sdbm"
unless ARGV.length == 3
fail "usage: dbmmerge indb1 indb2 outdb"
end
infile1 = ARGV[0]
infile2 = ARGV[0]
outfile = ARGV[2]
in1 = SDBM.open(infile1, nil)
in2 = SDBM.open(infile2, nil)
outdb = SDBM.open(outfile, 0666)
[in1, in2].each { |indb|
indb.each { |key, val|
if outdb.has_key?(key)
else
outdb[key] = val
end
}
}
in1.close
in2.close
outdb.close
class Array
def tie(filename, flags)
File.open(filename, flags) { |f|
f.each_line { |line|
self.push(line.chomp)
}
yield
f.rewind
each { |line|
if line
f.puts(line)
else
f.puts ""
end
}
}
end
end
array = Array.new
array.tie("/tmp/textfile.txt", File::RDWR|File::CREAT) {
array[4] = "a new line 4"
}
filename = "db_file.txt"
lines = Array.new
File.unlink(filename) if File.exists?(filename)
lines.tie(filename, File::RDWR | File::CREAT) {
lines[0] = "zero"
lines[1] = "one"
lines[2] = "two"
lines[3] = "three"
lines[4] = "four"
puts "\nOriginal"
for i in 0..(lines.length-1)
puts "#{i}: #{lines[i]}"
end
a = lines.pop
lines.push("last")
puts("The last line was [#{a}]")
a = lines.shift
lines.unshift("first")
puts("The first line was [#{a}]")
i = 2
lines.insert(i + 1, "Newbie")
i = 1
lines.insert(i, "New One")
lines.delete_at(3)
puts "\nReverse"
(lines.length - 1).downto(0){ |i|
puts "#{i}: #{lines[i]}"
}
}
require "sdbm"
db = SDBM.open("pleac14-8-database", 0666)
db["Tom Christiansen"] = Marshal.dump(["book author", "tchrist@perl.com"])
db["Tom Boutell"] = Marshal.dump(["shareware author",
"boutell@boutell.com"])
name1 = "Tom Christiansen"
name2 = "Tom Boutell"
tom1 = Marshal.load(db[name1])
tom2 = Marshal.load(db[name2])
puts "Two Toming: #{tom1} #{tom2}"
if tom1[0] == tom2[0] && tom1[1] == tom2[1]
puts "You're having runtime fun with one Tom made two."
else
puts "No two Toms are ever alike"
end
entry = Marshal.load(db["Tom Boutell"])
entry[0] = "Poet Programmer"
db["Tom Boutell"] = Marshal.dump(entry)
db.close
BEGIN {
$persistent_store = "persitence.dat"
begin
File.open($persistent_store) do |f|
$stringvariable1 = Marshal.load(f)
$arrayvariable2 = Marshal.load(f)
end
rescue
puts "Can not open #{$persistent_store}"
$stringvariable1 = ""
$arrayvariable2 = []
end
}
END {
File.open($persistent_store, "w+") do |f|
Marshal.dump($stringvariable1, f)
Marshal.dump($arrayvariable2, f)
end
}
puts $stringvariable1
puts $arrayvariable2
$stringvariable1 = "Hello World"
$arrayvariable2.push(5)
puts $stringvariable1
puts $arrayvariable2
begin
DBI.connect("DBI:driver:driverspecific", "username", "auth") {
|dbh|
dbh.do(SQL1)
dbh.prepare(SQL2){ |sth|
sth.execute
sth.fetch {|row|
}
} } rescue DBI::DatabaseError => e
puts "dbi error occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
end
require "dbi"
def getpwent
result = []
File.open("/etc/passwd") {|file|
file.each_line {|line|
next if line.match(/^#/)
cols = line.split(":")
result.push([cols[2], cols[0]])
}
}
result
end
begin
DBI.connect("DBI:Mysql:pleacdatabase", "pleac", "pleacpassword") {
|conn|
conn.do("CREATE TABLE users (uid INT, login CHAR(8))")
users = getpwent
conn.prepare("INSERT INTO users VALUES (?,?)") {|sth|
users.each {|entry|
sth.execute(entry[0], entry[1])
}
}
conn.execute("SELECT uid, login FROM users WHERE uid < 50") {|sth|
sth.fetch {|row|
puts row.collect {|col|
if col.nil?
"(null)"
else
col
end
}.join(", ")
}
}
conn.do("DROP TABLE users")
}
rescue DBI::DatabaseError => e
puts "dbi error occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
end
require 'optparse'
@debugmode = false
@verbose = false
ARGV.options do |opts|
opts.banner = "Usage: ruby #{$0} [OPTIONS] INPUTFILES"
opts.on("-h", "--help", "show this message") {
puts opts
exit
}
opts.on("-v", "--[no-]verbose=[FLAG]", TrueClass, "run verbosly") {
|@verbose| }
opts.on("-D", "--DEBUG", TrueClass, "turns on debug mode" ){
|@debugmode| }
opts.on("-c", "--count=NUMBER", Integer, "how many times we do it" ){
|@count| }
opts.on("-o", "--output=FILE", String, "file to write output to"){
|@outputfile| }
opts.parse!
end
puts "Verbose is on" if @verbose
puts "Debugmode is on" if @debugmode
puts "Outfile is #{@outputfile}" if defined? @outputfile
puts "Count is #{@count}" if defined? @count
ARGV.each { |param|
puts "Got parameter #{param}"
}
buf = "\0" * 8
$stdout.ioctl(0x5413, buf)
ws_row, ws_col, ws_xpixel, ws_ypixel = buf.unpack("S4")
raise "You must have at least 20 characters" unless ws_col >= 20
max = 0
values = (1..5).collect { rand(20) } for i in values
max = i if max < i
end
ratio = Float(ws_col-12)/max for i in values
printf "%8.1f %s\n", i, "*" * (ratio*i)
end
require 'term/ansicolor'
include Term::ANSIColor
print red, "Danger Will Robinson!", reset, "\n"
print "This is just normal text\n"
print blink, "Do you hurt yet?", reset, "\n"
print red("Danger Will Ronbinson!"), "\n"
print red( on_black( "venom lack" )), "\n"
print red( on_yellow( "kill that fellow" )), "\n"
print green( on_cyan( blink( "garish!" ))), "\n"
print red { "Danger Will Robinson!" }, "\n"
print red { on_black { "venom lack" } }, "\n"
print red { on_yellow { "kill that fellow" } }, "\n"
class String
include Term::ANSIColor
end
print "Danger Will Robinson!".red, "\n"
print "venom lack".red.on_black, "\n"
print "kill that fellow".red.on_yellow, "\n"
BLACK = "\e[30m"
RED = "\e[31m"
GREEN = "\e[32m"
WHITE = "\e[37m"
ON_BLACK = "\e[40m"
ON_WHITE = "\e[47m"
ON_YELLOW = "\e[43m"
ON_CYAN = "\e[46m"
BLINK = "\e[5m"
NOBLINK = "\e[25m"
BOLD = "\e[1m"
NOBOLD = "\e[22m"
RESET = "\e[0m"
puts "#{RED}Danger Will Ronbinson!#{RESET}"
puts "This is just normal text."
puts "#{BLINK}Do you hurt yet?#{NOBLINK}"
puts "#{RED}Danger Will Ronbinson!#{RESET}"
puts "#{RED}#{ON_BLACK}venom lack"
puts "#{RED}#{ON_YELLOW}kill that fellow"
puts "#{GREEN}#{ON_CYAN}#{BLINK}garish!"
print BLACK, ON_WHITE, "black on white\n"
print WHITE, ON_BLACK, "white on black\n"
print GREEN, ON_CYAN, BLINK, "garish!\n"
print RESET
output = `program args` output = `program args`.to_a
output = ""
IO.popen("ls") do |readme|
readme.each do |line|
output << line
end
end
`fsck -y /dev/rsd1a`
readme, writeme = IO.pipe
pid = fork {
$stdout.reopen writeme
readme.close
exec('find', '..')
}
writeme.close
readme.each do |line|
end
Process.waitpid(pid)
status = system("xemacs #{myfile}")
status = system("xemacs", myfile)
system("cmd1 args | cmd2 | cmd3 >outfile")
system("cmd args <infile >outfile 2>errfile")
abort "$program exited funny: #{$?}" unless system("cmd", "args1", "args2")
arglist = ['ruby', '-e', '5.times {|i| p i}']
system(*arglist)
raise "program killed by signal #{$?}" if ($? & 127) != 0
pid = fork {
trap("SIGINT", "IGNORE")
exec("sleep", "10")
}
trap ("SIGINT") {
puts "Tsk tsk, no process interruptus"
}
Process.waitpid(pid, 0)
system ['bash', 'fake'], '-c', 'echo $0'
exec("archive *.data")
exec("archive", "accounting.data")
exec("archive accounting.data")
IO.popen("ls") {|readme|
while readme.gets do
end
}
readme = IO.popen("ls")
while readme.gets do
end
readme.close
IO.popen("cmd args","w") {|pipe|
pipe.puts("data")
pipe.puts("foo")
}
read = IO.popen("sleep 10000") read.close
writeme = IO.popen("cmd args", "w")
writeme.puts "hello" writeme.close
$stdout = IO.popen("/usr/bin/less","w")
print "huge string\n" * 10000
def head(lines = 20)
pid = open("|-","w")
if pid == nil
return
else
while gets() do
pid.print
lines -= 1
break if lines == 0
end
end
exit
end
head(100)
while gets() do
print
end
1: > Welcome to Linux, version 2.0.33 on a i686
2: >
3: > "The software required `Windows 95 or better',
4: > so I installed Linux."
> 1: Welcome to Linux, Kernel version 2.0.33 on a i686
> 2:
> 3: "The software required `Windows 95 or better',
> 4: so I installed Linux."
def number()
pid = open("|-","w")
if pid == nil
return
else
while gets() do pid.printf("%d: %s", $., $_); end
end
exit
end
def quote()
pid = open("|-","w")
if pid == nil
return
else
while gets() do pid.print "> #{$_}" end
end
exit
end
number()
quote()
while gets() do
print
end
$stdout.close
exit
ARGV.map! { |arg|
arg =~ /\.(gz|Z)$/ ? "|gzip -dc #{arg}" : arg
}
for file in ARGV
fh = open(file)
while fh.gets() do
end
end
ARGV.map! { |arg|
arg =~ %r#{arg}}
for file in ARGV
fh = open(file)
while fh.gets() do
end
end
pwdinfo = (`domainname` =~ /^(\(none\))?$/) ? '/etc/passwd' : '|ypcat passwd';
pwd = open(pwdinfo);
puts "File, please? ";
file = gets().chomp();
fh = open(file);
output = `cmd 2>&1` ph = open("|cmd 2>&1") while ph.gets() { } output = `cmd 2>/dev/null` ph = open("|cmd 2>/dev/null") while ph.gets() { } output = `cmd 2>&1 1>/dev/null` ph = open("|cmd 2>&1 1>/dev/null") while ph.gets() { } output = `cmd 3>&1 1>&2 2>&3 3>&-` ph = open("|cmd 3>&1 1>&2 2>&3 3>&-") while ph.gets() { } system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr")
output = `cmd 3>&1 1>&2 2>&3 3>&-`
fd3 = fd1
fd1 = fd2
fd2 = fd3
fd3 = undef
system("prog args 1>tmpfile 2>&1")
system("prog args 2>&1 1>tmpfile")
fd1 = "tmpfile" fd2 = fd1 fd2 = fd1 fd1 = "tmpfile" require "open3"
stdin, stdout, stderr = Open3.popen('cmd')
fh = Kernel.open("|" + program, "w+")
fh.puts "here's your input\n"
output = fh.gets()
fh.close()
Kernel.open("|program"),"w+") begin
fh = Kernel.open("|" + program_and_options, "w+")
rescue
if ($@ ~= /^open/)
$stderr.puts "open failed : #{$!} \n #{$@} \n"
break
end
raise end
signame = []
Signal.list.each { |name, i| signame[i] = name }
Process.kill(9, pid) Process.kill(-1, Process.getpgrp()) Process.kill("USR1", $$) Process.kill("HUP", pid1, pid2, pid3) begin
Process.kill(0, minion)
puts "#{minion} is alive!"
rescue Errno::EPERM puts "#{minion} has escaped my control!";
rescue Errno::ESRCH
puts "#{minion} is deceased."; rescue
puts "Odd; I couldn't check the status of #{minion} : #{$!}"
end
Kernel.trap("QUIT", got_sig_quit) trap("PIPE", "got_sig_quit") trap("INT") { ouch++ } trap("INT", "IGNORE") trap("STOP", "DEFAULT")
def ding
trap("INT", "ding")
puts "\aEnter your name!"
end
def get_name
save = trap("INT", "ding")
puts "Kindly Stranger, please enter your name: "
name = gets().chomp()
trap("INT", save)
name
end
require 'timeout'
begin
timeout(5) {
waitsec = rand(10)
puts "Let's see if a sleep of #{waitsec} seconds is longer than 5 seconds..."
system("sleep #{waitsec}")
}
puts "Timeout didn't occur"
rescue Timeout::Error
puts "Timed out!"
end
require 'socket'
begin
t = TCPSocket.new('www.ruby-lang.org', 'www')
rescue
puts "error: #{$!}"
else
t.print "GET / HTTP/1.0\n\n"
answer = t.gets(nil)
t.close
end
require 'socket'
s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
sockaddr_server = [Socket::AF_INET, 80,
Socket.gethostbyname('www.ruby-lang.org')[3],
0, 0].pack("snA4NN")
begin
s.connect(sockaddr_server)
rescue
puts "error: #{$!}"
else
s.print "GET / HTTP/1.0\n\n"
s.close
end
require 'socket'
begin
client = TCPSocket.new('does not exists', 'www')
rescue
puts "error: #{$!}"
end
require 'socket'
require 'timeout'
begin
timeout(1) do client = TCPSocket.new('www.host.com', 'www')
end
rescue
puts "error: #{$!}"
end
require 'socket'
class Preforker
attr_reader (:child_count)
def initialize(prefork, max_clients_per_child, port, client_handler)
@prefork = prefork
@max_clients_per_child = max_clients_per_child
@port = port
@child_count = 0
@reaper = proc {
trap('CHLD', @reaper)
pid = Process.wait
@child_count -= 1
}
@huntsman = proc {
trap('CHLD', 'IGNORE')
trap('INT', 'IGNORE')
Process.kill('INT', 0)
exit
}
@client_handler=client_handler
end
def child_handler
trap('INT', 'EXIT')
@client_handler.setUp
@max_clients_per_child.times {
client = @server.accept or break
@client_handler.handle_request(client)
client.close
}
@client_handler.tearDown
end
def make_new_child
@child_count += 1
pid = fork do
child_handler
end
end
def run
@server = TCPserver.open(@port)
trap('CHLD', @reaper)
trap('INT', @huntsman)
loop {
(@prefork - @child_count).times { |i|
make_new_child
}
sleep .1
}
end
end
require 'Preforker'
class ClientHandler
def setUp
end
def tearDown
end
def handle_request(client)
end
end
server = Preforker.new(1, 100, 3102, ClientHandler.new)
server.run
require 'net/ftp'
begin
ftp = Net::FTP::new("ftp.host.com")
ftp.login(username,password)
ftp.chdir(directory)
ftp.get(filename)
ftp.put(filename)
rescue Net::FTPError
$stderr.print "FTP failed: " + $!
ensure
ftp.close() if ftp
end
Net::FTP::new("ftp.host.com") do |ftp|
ftp.login(username,password)
ftp.chdir(directory)
ftp.get(filename)
ftp.put(filename)
end
require 'open-uri'
open("ftp://www.ruby-lang.org/path/filename") do |fh|
end
require 'timeout'
begin
timeout(30){
ftp = Net::FTP::new("ftp.host.com")
ftp.debug_mode = true
}
rescue Net::FTPError
$stderr.puts "Couldn't connect."
rescue Timeout::Error
$stderr.puts "Timeout while connecting to server."
end
begin
ftp.login()
rescue Net::FTPError
$stderr.print "Couldn't authentificate.\n"
end
begin
ftp.login(username)
rescue Net::FTPError
$stderr.print "Still couldn't authenticate.\n"
end
begin
ftp.login(username, password)
rescue Net::FTPError
$stderr.print "Couldn't authenticate, even with explicit
username and password.\n"
end
begin
ftp.login(username, password, account)
rescue Net::FTPError
$stderr.print "No dice. It hates me.\n"
end
ftp.put(localfile, remotefile)
ftp.get(remotefile, localfile)
ftp.get(remotefile) { |data| puts data }
ftp.chdir("/pub/ruby")
print "I'm in the directory ", ftp.pwd(), "\n"
ftp.mkdir("/pub/ruby/new_dir")
lines = ftp.ls("/pub/ruby/")
latest = ftp.dir("/pub/ruby/*.tgz").sort.last
ftp.nlst("/pub/ruby")
ftp.quit()
require 'net/telnet'
t = Net::Telnet::new( "Timeout" => 10,
"Prompt" => /%/,
"Host" => host )
t.login(username, password)
files = t.cmd("ls")
t.print("top")
process_string = t.waitfor(/\d+ processes/)
t.close
/[$%#>] \z/n
begin
telnet.login(username, password)
rescue TimeoutError
fail "Login failed !\n"
end
telnet.waitfor('/--more--/')
telnet.waitfor(String => 'greasy smoke', Timeout => 30)
require 'ping'
puts "#{host} is alive.\n" if Ping.pingecho(host);
if Ping.pingecho("kingkong.com")
puts "The giant ape lives!\n";
else
puts "All hail mighty Gamera, friend of children!\n";
end
require 'cgi'
cgi = CGI.new('html3')
value = cgi.params['PARAM_NAME'][0]
cgi.out {
cgi.html {
cgi.head { cgi.title { "Howdy there!" } } +
cgi.body { cgi.p { "You typed: " + cgi.tt {
CGI.escapeHTML(value) } } }
}
}
require 'cgi'
cgi = CGI.new
who = cgi.param["Name"][0] phone = cgi.param["Number"][0]
picks = cgi.param["Choices"]
print cgi.header( 'type' => 'text/plain',
'expires' => Time.now + (3 * 24 * 60 * 60) )
require 'etc'
print "Content-Type: text/plain\n\n"
print "Running as " + Etc.getpwuid.name + "\n"
$SAFE = 1
File.open(ARGV[0], "w")
$SAFE = 1
file = ARGV[0]
unless /^([\w.-]+)$/.match(file)
raise "filename #{file} has invalid characters"
end
file = $1
file.untaint
File.open(file, "w")
unless File.exists(filename) File.open(filename, "w")
end
url = "http://pleac.sourceforge.net/pleac_ruby/"
print "Location: #{url}\r\n\r\n"
exit
require 'cgi'
cgi = CGI.new
oreo = CGI::Cookie.new('name' => 'filling',
'value' => 'vanilla creme',
'expires' => Time.now + (3 * 30 * 24 * 60 * 60),
'domain' => '.pleac.sourceforge.net')
whither = 'http://pleac.sourceforge.net/pleac_ruby/cgiprogramming.html'
cgi.out('cookie' => oreo,
'Location' => whither){""}
dir = 'http://www.elsewhere.org/jargon/html/entry'
agent = ENV['HTTP_USER_AGENT']
page = case
when agent =~ /Mac/: 'Macintrash.html'
when agent =~ /Win(dows )?NT/: 'evil_and_rude.html'
when agent =~ /Win|MSIE|WebTV/: 'Microsloth_Windows.html'
when agent =~ /Linux/: 'Linux.html'
when agent =~ /HP-UX/: 'HP-SUX.html'
when agent =~ /SunOS/: 'ScumOS.html'
else 'Appendix_B.html'
end
print "Location: #{dir}/#{page}\n\n"
require 'cgi'
cgi = CGI.new
cgi.out('status' => '204 No response'){""}
preference_value = cgi.cookies["preference name"][0]
packed_cookie = CGI::Cookie.new("name" => "preference name",
"value" => "whatever you'd like",
"expires" => Time.local(Time.now.year + 2,
Time.now.mon, Time.now.day, Time.now.hour, Time.now.min, Time.now.sec) )
cgi.header("cookie" => [packed_cookie])
require 'cgi'
cgi = CGI.new('html3')
cookname = "favorite ice cream"
favorite = cgi.params["flavor"][0]
tasty = cgi.cookies[cookname][0] || 'mint'
unless favorite
cgi.out {
cgi.html {
cgi.head { cgi.title { "Ice Cookies" } } +
cgi.body {
cgi.h1 { "Hello Ice Cream" } +
cgi.hr +
cgi.form {
cgi.p { "Please select a flavor: " +
cgi.text_field("flavor", tasty ) }
} +
cgi.hr
}
}
}
else
cookie = CGI::Cookie.new( "name" => cookname,
"value" => favorite,
"expires" => Time.local(Time.now.year + 2,
Time.now.mon, Time.now.day, Time.now.hour, Time.now.min, Time.now.sec) )
cgi.out("cookie" => [cookie]) {
cgi.html {
cgi.head { cgi.title { "Ice Cookies" } } +
cgi.body {
cgi.h1 { "Hello Ice Cream" } +
cgi.p { "You chose as your favorite flavor `#{favorite}'." }
}
}
}
end
def templatefile(filename, fillings)
aFile = File.new(filename, "r")
text = aFile.read()
aFile.close()
pattern = Regexp.new('%%(.*?)%%')
text.gsub!(pattern) {
fillings[$1] || ""
}
text
end
fields = {
'username' => whats_his_name,
'count' => login_count,
'total' => minutes_used
}
puts templatefile('simple.template', fields)