Debian Codegraph @

bench/example.ruby

raw
1 module CodeRay
2 module Scanners
3
4 class Ruby < Scanner
5
6 RESERVED_WORDS = [
7 'and', 'def', 'end', 'in', 'or', 'unless', 'begin',
8 'defined?', 'ensure', 'module', 'redo', 'super', 'until',
9 'BEGIN', 'break', 'do', 'next', 'rescue', 'then',
10 'when', 'END', 'case', 'else', 'for', 'retry',
11 'while', 'alias', 'class', 'elsif', 'if', 'not', 'return',
12 'undef', 'yield',
13 ]
14
15 DEF_KEYWORDS = ['def']
16 MODULE_KEYWORDS = ['class', 'module']
17 DEF_NEW_STATE = WordList.new(:initial).
18 add(DEF_KEYWORDS, :def_expected).
19 add(MODULE_KEYWORDS, :module_expected)
20
21 WORDS_ALLOWING_REGEXP = [
22 'and', 'or', 'not', 'while', 'until', 'unless', 'if', 'elsif', 'when'
23 ]
24 REGEXP_ALLOWED = WordList.new(false).
25 add(WORDS_ALLOWING_REGEXP, :set)
26
27 PREDEFINED_CONSTANTS = [
28 'nil', 'true', 'false', 'self',
29 'DATA', 'ARGV', 'ARGF', '__FILE__', '__LINE__',
30 ]
31
32 IDENT_KIND = WordList.new(:ident).
33 add(RESERVED_WORDS, :reserved).
34 add(PREDEFINED_CONSTANTS, :pre_constant)
35
36 METHOD_NAME = / #{IDENT} [?!]? /xo
37 METHOD_NAME_EX = /
38 #{METHOD_NAME} # common methods: split, foo=, empty?, gsub!
39 | \*\*? # multiplication and power
40 | [-+~]@? # plus, minus
41 | [\/%&|^`] # division, modulo or format strings, &and, |or, ^xor, `system`
42 | \[\]=? # array getter and setter
43 | <=?>? | >=? # comparison, rocket operator
44 | << | >> # append or shift left, shift right
45 | ===? # simple equality and case equality
46 /ox
47 GLOBAL_VARIABLE = / \$ (?: #{IDENT} | \d+ | [~&+`'=\/,;_.<>!@0$?*":F\\] | -[a-zA-Z_0-9] ) /ox
48
49 DOUBLEQ = / " [^"\#\\]* (?: (?: \#\{.*?\} | \#(?:$")? | \\. ) [^"\#\\]* )* "? /ox
50 SINGLEQ = / ' [^'\\]* (?: \\. [^'\\]* )* '? /ox
51 STRING = / #{SINGLEQ} | #{DOUBLEQ} /ox
52 SHELL = / ` [^`\#\\]* (?: (?: \#\{.*?\} | \#(?:$`)? | \\. ) [^`\#\\]* )* `? /ox
53 REGEXP = / \/ [^\/\#\\]* (?: (?: \#\{.*?\} | \#(?:$\/)? | \\. ) [^\/\#\\]* )* \/? /ox
54
55 DECIMAL = /\d+(?:_\d+)*/ # doesn't recognize 09 as octal error
56 OCTAL = /0_?[0-7]+(?:_[0-7]+)*/
57 HEXADECIMAL = /0x[0-9A-Fa-f]+(?:_[0-9A-Fa-f]+)*/
58 BINARY = /0b[01]+(?:_[01]+)*/
59
60 EXPONENT = / [eE] [+-]? #{DECIMAL} /ox
61 FLOAT = / #{DECIMAL} (?: #{EXPONENT} | \. #{DECIMAL} #{EXPONENT}? ) /
62 INTEGER = /#{OCTAL}|#{HEXADECIMAL}|#{BINARY}|#{DECIMAL}/
63
64 def reset
65 super
66 @regexp_allowed = false
67 end
68
69 def next_token
70 return if @scanner.eos?
71
72 kind = :error
73 if @scanner.scan(/\s+/) # in every state
74 kind = :space
75 @regexp_allowed = :set if @regexp_allowed or @scanner.matched.index(?\n) # delayed flag setting
76
77 elsif @state == :def_expected
78 if @scanner.scan(/ (?: (?:#{IDENT}(?:\.|::))* | (?:@@?|$)? #{IDENT}(?:\.|::) ) #{METHOD_NAME_EX} /ox)
79 kind = :method
80 @state = :initial
81 else
82 @scanner.getch
83 end
84 @state = :initial
85
86 elsif @state == :module_expected
87 if @scanner.scan(/<</)
88 kind = :operator
89 else
90 if @scanner.scan(/ (?: #{IDENT} (?:\.|::))* #{IDENT} /ox)
91 kind = :method
92 else
93 @scanner.getch
94 end
95 @state = :initial
96 end
97
98 elsif # state == :initial
99 # IDENTIFIERS, KEYWORDS
100 if @scanner.scan(GLOBAL_VARIABLE)
101 kind = :global_variable
102 elsif @scanner.scan(/ @@ #{IDENT} /ox)
103 kind = :class_variable
104 elsif @scanner.scan(/ @ #{IDENT} /ox)
105 kind = :instance_variable
106 elsif @scanner.scan(/ __END__\n ( (?!\#CODE\#) .* )? | \#[^\n]* | =begin(?=\s).*? \n=end(?=\s|\z)(?:[^\n]*)? /mx)
107 kind = :comment
108 elsif @scanner.scan(METHOD_NAME)
109 if @last_token_dot
110 kind = :ident
111 else
112 matched = @scanner.matched
113 kind = IDENT_KIND[matched]
114 if kind == :ident and matched =~ /^[A-Z]/
115 kind = :constant
116 elsif kind == :reserved
117 @state = DEF_NEW_STATE[matched]
118 @regexp_allowed = REGEXP_ALLOWED[matched]
119 end
120 end
121
122 elsif @scanner.scan(STRING)
123 kind = :string
124 elsif @scanner.scan(SHELL)
125 kind = :shell
126 elsif @scanner.scan(/<<
127 (?:
128 ([a-zA-Z_0-9]+)
129 (?: .*? ^\1$ | .* )
130 |
131 -([a-zA-Z_0-9]+)
132 (?: .*? ^\s*\2$ | .* )
133 |
134 (["\'`]) (.+?) \3
135 (?: .*? ^\4$ | .* )
136 |
137 - (["\'`]) (.+?) \5
138 (?: .*? ^\s*\6$ | .* )
139 )
140 /mxo)
141 kind = :string
142 elsif @scanner.scan(/\//) and @regexp_allowed
143 @scanner.unscan
144 @scanner.scan(REGEXP)
145 kind = :regexp
146 /%(?:[Qqxrw](?:\([^)#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^)#\\\\]*)*\)?|\[[^\]#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^\]#\\\\]*)*\]?|\{[^}#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^}#\\\\]*)*\}?|<[^>#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^>#\\\\]*)*>?|([^a-zA-Z\\\\])(?:(?!\1)[^#\\\\])*(?:(?:#\{.*?\}|#|\\\\.)(?:(?!\1)[^#\\\\])*)*\1?)|\([^)#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^)#\\\\]*)*\)?|\[[^\]#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^\]#\\\\]*)*\]?|\{[^}#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^}#\\\\]*)*\}?|<[^>#\\\\]*(?:(?:#\{.*?\}|#|\\\\.)[^>#\\\\]*)*>?|([^a-zA-Z\s\\\\])(?:(?!\2)[^#\\\\])*(?:(?:#\{.*?\}|#|\\\\.)(?:(?!\2)[^#\\\\])*)*\2?|\\\\[^#\\\\]*(?:(?:#\{.*?\}|#)[^#\\\\]*)*\\\\?)/
147 elsif @scanner.scan(/:(?:#{GLOBAL_VARIABLE}|#{METHOD_NAME_EX}|#{STRING})/ox)
148 kind = :symbol
149 elsif @scanner.scan(/
150 \? (?:
151 [^\s\\]
152 |
153 \\ (?:M-\\C-|C-\\M-|M-\\c|c\\M-|c|C-|M-))? (?: \\ (?: . | [0-7]{3} | x[0-9A-Fa-f][0-9A-Fa-f] )
154 )
155 /mox)
156 kind = :integer
157
158 elsif @scanner.scan(/ [-+*\/%=<>;,|&!()\[\]{}~?] | \.\.?\.? | ::? /x)
159 kind = :operator
160 @regexp_allowed = :set if @scanner.matched[-1,1] =~ /[~=!<>|&^,\(\[+\-\/\*%]\z/
161 elsif @scanner.scan(FLOAT)
162 kind = :float
163 elsif @scanner.scan(INTEGER)
164 kind = :integer
165 else
166 @scanner.getch
167 end
168 end
169
170 token = Token.new @scanner.matched, kind
171
172 if kind == :regexp
173 token.text << @scanner.scan(/[eimnosux]*/)
174 end
175
176 @regexp_allowed = (@regexp_allowed == :set) # delayed flag setting
177
178 token
179 end
180 end
181
182 register Ruby, 'ruby', 'rb'
183
184 end
185 end
186 class Set
187 include Enumerable
188
189 # Creates a new set containing the given objects.
190 def self.[](*ary)
191 new(ary)
192 end
193
194 # Creates a new set containing the elements of the given enumerable
195 # object.
196 #
197 # If a block is given, the elements of enum are preprocessed by the
198 # given block.
199 def initialize(enum = nil, &block) # :yields: o
200 @hash ||= Hash.new
201
202 enum.nil? and return
203
204 if block
205 enum.each { |o| add(block[o]) }
206 else
207 merge(enum)
208 end
209 end
210
211 # Copy internal hash.
212 def initialize_copy(orig)
213 @hash = orig.instance_eval{@hash}.dup
214 end
215
216 # Returns the number of elements.
217 def size
218 @hash.size
219 end
220 alias length size
221
222 # Returns true if the set contains no elements.
223 def empty?
224 @hash.empty?
225 end
226
227 # Removes all elements and returns self.
228 def clear
229 @hash.clear
230 self
231 end
232
233 # Replaces the contents of the set with the contents of the given
234 # enumerable object and returns self.
235 def replace(enum)
236 if enum.class == self.class
237 @hash.replace(enum.instance_eval { @hash })
238 else
239 enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
240 clear
241 enum.each { |o| add(o) }
242 end
243
244 self
245 end
246
247 # Converts the set to an array. The order of elements is uncertain.
248 def to_a
249 @hash.keys
250 end
251
252 def flatten_merge(set, seen = Set.new)
253 set.each { |e|
254 if e.is_a?(Set)
255 if seen.include?(e_id = e.object_id)
256 raise ArgumentError, "tried to flatten recursive Set"
257 end
258
259 seen.add(e_id)
260 flatten_merge(e, seen)
261 seen.delete(e_id)
262 else
263 add(e)
264 end
265 }
266
267 self
268 end
269 protected :flatten_merge
270
271 # Returns a new set that is a copy of the set, flattening each
272 # containing set recursively.
273 def flatten
274 self.class.new.flatten_merge(self)
275 end
276
277 # Equivalent to Set#flatten, but replaces the receiver with the
278 # result in place. Returns nil if no modifications were made.
279 def flatten!
280 if detect { |e| e.is_a?(Set) }
281 replace(flatten())
282 else
283 nil
284 end
285 end
286
287 # Returns true if the set contains the given object.
288 def include?(o)
289 @hash.include?(o)
290 end
291 alias member? include?
292
293 # Returns true if the set is a superset of the given set.
294 def superset?(set)
295 set.is_a?(Set) or raise ArgumentError, "value must be a set"
296 return false if size < set.size
297 set.all? { |o| include?(o) }
298 end
299
300 # Returns true if the set is a proper superset of the given set.
301 def proper_superset?(set)
302 set.is_a?(Set) or raise ArgumentError, "value must be a set"
303 return false if size <= set.size
304 set.all? { |o| include?(o) }
305 end
306
307 # Returns true if the set is a subset of the given set.
308 def subset?(set)
309 set.is_a?(Set) or raise ArgumentError, "value must be a set"
310 return false if set.size < size
311 all? { |o| set.include?(o) }
312 end
313
314 # Returns true if the set is a proper subset of the given set.
315 def proper_subset?(set)
316 set.is_a?(Set) or raise ArgumentError, "value must be a set"
317 return false if set.size <= size
318 all? { |o| set.include?(o) }
319 end
320
321 # Calls the given block once for each element in the set, passing
322 # the element as parameter.
323 def each
324 @hash.each_key { |o| yield(o) }
325 self
326 end
327
328 # Adds the given object to the set and returns self. Use +merge+ to
329 # add several elements at once.
330 def add(o)
331 @hash[o] = true
332 self
333 end
334 alias << add
335
336 # Adds the given object to the set and returns self. If the
337 # object is already in the set, returns nil.
338 def add?(o)
339 if include?(o)
340 nil
341 else
342 add(o)
343 end
344 end
345
346 # Deletes the given object from the set and returns self. Use +subtract+ to
347 # delete several items at once.
348 def delete(o)
349 @hash.delete(o)
350 self
351 end
352
353 # Deletes the given object from the set and returns self. If the
354 # object is not in the set, returns nil.
355 def delete?(o)
356 if include?(o)
357 delete(o)
358 else
359 nil
360 end
361 end
362
363 # Deletes every element of the set for which block evaluates to
364 # true, and returns self.
365 def delete_if
366 @hash.delete_if { |o,| yield(o) }
367 self
368 end
369
370 # Do collect() destructively.
371 def collect!
372 set = self.class.new
373 each { |o| set << yield(o) }
374 replace(set)
375 end
376 alias map! collect!
377
378 # Equivalent to Set#delete_if, but returns nil if no changes were
379 # made.
380 def reject!
381 n = size
382 delete_if { |o| yield(o) }
383 size == n ? nil : self
384 end
385
386 # Merges the elements of the given enumerable object to the set and
387 # returns self.
388 def merge(enum)
389 if enum.is_a?(Set)
390 @hash.update(enum.instance_eval { @hash })
391 else
392 enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
393 enum.each { |o| add(o) }
394 end
395
396 self
397 end
398
399 # Deletes every element that appears in the given enumerable object
400 # and returns self.
401 def subtract(enum)
402 enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
403 enum.each { |o| delete(o) }
404 self
405 end
406
407 # Returns a new set built by merging the set and the elements of the
408 # given enumerable object.
409 def |(enum)
410 enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
411 dup.merge(enum)
412 end
413 alias + | ##
414 alias union | ##
415
416 # Returns a new set built by duplicating the set, removing every
417 # element that appears in the given enumerable object.
418 def -(enum)
419 enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
420 dup.subtract(enum)
421 end
422 alias difference - ##
423
424 # Returns a new array containing elements common to the set and the
425 # given enumerable object.
426 def &(enum)
427 enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
428 n = self.class.new
429 enum.each { |o| n.add(o) if include?(o) }
430 n
431 end
432 alias intersection & ##
433
434 # Returns a new array containing elements exclusive between the set
435 # and the given enumerable object. (set ^ enum) is equivalent to
436 # ((set | enum) - (set & enum)).
437 def ^(enum)
438 enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
439 n = dup
440 enum.each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
441 n
442 end
443
444 # Returns true if two sets are equal. The equality of each couple
445 # of elements is defined according to Object#eql?.
446 def ==(set)
447 equal?(set) and return true
448
449 set.is_a?(Set) && size == set.size or return false
450
451 hash = @hash.dup
452 set.all? { |o| hash.include?(o) }
453 end
454
455 def hash # :nodoc:
456 @hash.hash
457 end
458
459 def eql?(o) # :nodoc:
460 return false unless o.is_a?(Set)
461 @hash.eql?(o.instance_eval{@hash})
462 end
463
464 # Classifies the set by the return value of the given block and
465 # returns a hash of {value => set of elements} pairs. The block is
466 # called once for each element of the set, passing the element as
467 # parameter.
468 #
469 # e.g.:
470 #
471 # require 'set'
472 # files = Set.new(Dir.glob("*.rb"))
473 # hash = files.classify { |f| File.mtime(f).year }
474 # p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
475 # # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
476 # # 2002=>#<Set: {"f.rb"}>}
477 def classify # :yields: o
478 h = {}
479
480 each { |i|
481 x = yield(i)
482 (h[x] ||= self.class.new).add(i)
483 }
484
485 h
486 end
487
488 # Divides the set into a set of subsets according to the commonality
489 # defined by the given block.
490 #
491 # If the arity of the block is 2, elements o1 and o2 are in common
492 # if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
493 # in common if block.call(o1) == block.call(o2).
494 #
495 # e.g.:
496 #
497 # require 'set'
498 # numbers = Set[1, 3, 4, 6, 9, 10, 11]
499 # set = numbers.divide { |i,j| (i - j).abs == 1 }
500 # p set # => #<Set: {#<Set: {1}>,
501 # # #<Set: {11, 9, 10}>,
502 # # #<Set: {3, 4}>,
503 # # #<Set: {6}>}>
504 def divide(&func)
505 if func.arity == 2
506 require 'tsort'
507
508 class << dig = {} # :nodoc:
509 include TSort
510
511 alias tsort_each_node each_key
512 def tsort_each_child(node, &block)
513 fetch(node).each(&block)
514 end
515 end
516
517 each { |u|
518 dig[u] = a = []
519 each{ |v| func.call(u, v) and a << v }
520 }
521
522 set = Set.new()
523 dig.each_strongly_connected_component { |css|
524 set.add(self.class.new(css))
525 }
526 set
527 else
528 Set.new(classify(&func).values)
529 end
530 end
531
532 InspectKey = :__inspect_key__ # :nodoc:
533
534 # Returns a string containing a human-readable representation of the
535 # set. ("#<Set: {element1, element2, ...}>")
536 def inspect
537 ids = (Thread.current[InspectKey] ||= [])
538
539 if ids.include?(object_id)
540 return sprintf('#<%s: {...}>', self.class.name)
541 end
542
543 begin
544 ids << object_id
545 return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
546 ensure
547 ids.pop
548 end
549 end
550
551 def pretty_print(pp) # :nodoc:
552 pp.text sprintf('#<%s: {', self.class.name)
553 pp.nest(1) {
554 pp.seplist(self) { |o|
555 pp.pp o
556 }
557 }
558 pp.text "}>"
559 end
560
561 def pretty_print_cycle(pp) # :nodoc:
562 pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
563 end
564 end
565
566 # SortedSet implements a set which elements are sorted in order. See Set.
567 class SortedSet < Set
568 @@setup = false
569
570 class << self
571 def [](*ary) # :nodoc:
572 new(ary)
573 end
574
575 def setup # :nodoc:
576 @@setup and return
577
578 begin
579 require 'rbtree'
580
581 module_eval %{
582 def initialize(*args, &block)
583 @hash = RBTree.new
584 super
585 end
586 }
587 rescue LoadError
588 module_eval %{
589 def initialize(*args, &block)
590 @keys = nil
591 super
592 end
593
594 def clear
595 @keys = nil
596 super
597 end
598
599 def replace(enum)
600 @keys = nil
601 super
602 end
603
604 def add(o)
605 @keys = nil
606 @hash[o] = true
607 self
608 end
609 alias << add
610
611 def delete(o)
612 @keys = nil
613 @hash.delete(o)
614 self
615 end
616
617 def delete_if
618 n = @hash.size
619 @hash.delete_if { |o,| yield(o) }
620 @keys = nil if @hash.size != n
621 self
622 end
623
624 def merge(enum)
625 @keys = nil
626 super
627 end
628
629 def each
630 to_a.each { |o| yield(o) }
631 end
632
633 def to_a
634 (@keys = @hash.keys).sort! unless @keys
635 @keys
636 end
637 }
638 end
639
640 @@setup = true
641 end
642 end
643
644 def initialize(*args, &block) # :nodoc:
645 SortedSet.setup
646 initialize(*args, &block)
647 end
648 end
649
650 module Enumerable
651 # Makes a set from the enumerable object with given arguments.
652 def to_set(klass = Set, *args, &block)
653 klass.new(self, *args, &block)
654 end
655 end
656
657 # =begin
658 # == RestricedSet class
659 # RestricedSet implements a set with restrictions defined by a given
660 # block.
661 #
662 # === Super class
663 # Set
664 #
665 # === Class Methods
666 # --- RestricedSet::new(enum = nil) { |o| ... }
667 # --- RestricedSet::new(enum = nil) { |rset, o| ... }
668 # Creates a new restricted set containing the elements of the given
669 # enumerable object. Restrictions are defined by the given block.
670 #
671 # If the block's arity is 2, it is called with the RestrictedSet
672 # itself and an object to see if the object is allowed to be put in
673 # the set.
674 #
675 # Otherwise, the block is called with an object to see if the object
676 # is allowed to be put in the set.
677 #
678 # === Instance Methods
679 # --- restriction_proc
680 # Returns the restriction procedure of the set.
681 #
682 # =end
683 #
684 # class RestricedSet < Set
685 # def initialize(*args, &block)
686 # @proc = block or raise ArgumentError, "missing a block"
687 #
688 # if @proc.arity == 2
689 # instance_eval %{
690 # def add(o)
691 # @hash[o] = true if @proc.call(self, o)
692 # self
693 # end
694 # alias << add
695 #
696 # def add?(o)
697 # if include?(o) || [email protected](self, o)
698 # nil
699 # else
700 # @hash[o] = true
701 # self
702 # end
703 # end
704 #
705 # def replace(enum)
706 # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
707 # clear
708 # enum.each { |o| add(o) }
709 #
710 # self
711 # end
712 #
713 # def merge(enum)
714 # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
715 # enum.each { |o| add(o) }
716 #
717 # self
718 # end
719 # }
720 # else
721 # instance_eval %{
722 # def add(o)
723 # if @proc.call(o)
724 # @hash[o] = true
725 # end
726 # self
727 # end
728 # alias << add
729 #
730 # def add?(o)
731 # if include?(o) || [email protected](o)
732 # nil
733 # else
734 # @hash[o] = true
735 # self
736 # end
737 # end
738 # }
739 # end
740 #
741 # super(*args)
742 # end
743 #
744 # def restriction_proc
745 # @proc
746 # end
747 # end
748
749 if $0 == __FILE__
750 eval DATA.read, nil, $0, __LINE__+4
751 end
752
753 # = rweb - CGI Support Library
754 #
755 # Author:: Johannes Barre (mailto:[email protected])
756 # Copyright:: Copyright (c) 2003, 04 by Johannes Barre
757 # License:: GNU Lesser General Public License (COPYING, http://www.gnu.org/copyleft/lesser.html)
758 # Version:: 0.1.0
759 # CVS-ID:: $Id: rweb.rb 6 2004-06-16 15:56:26Z igel $
760 #
761 # == What is Rweb?
762 # Rweb is a replacement for the cgi class included in the ruby distribution.
763 #
764 # == How to use
765 #
766 # === Basics
767 #
768 # This class is made to be as easy as possible to use. An example:
769 #
770 # require "rweb"
771 #
772 # web = Rweb.new
773 # web.out do
774 # web.puts "Hello world!"
775 # end
776 #
777 # The visitor will get a simple "Hello World!" in his browser. Please notice,
778 # that won't set html-tags for you, so you should better do something like this:
779 #
780 # require "rweb"
781 #
782 # web = Rweb.new
783 # web.out do
784 # web.puts "<html><body>Hello world!</body></html>"
785 # end
786 #
787 # === Set headers
788 # Of course, it's also possible to tell the browser, that the content of this
789 # page is plain text instead of html code:
790 #
791 # require "rweb"
792 #
793 # web = Rweb.new
794 # web.out do
795 # web.header("content-type: text/plain")
796 # web.puts "Hello plain world!"
797 # end
798 #
799 # Please remember, headers can't be set after the page content has been send.
800 # You have to set all nessessary headers before the first puts oder print. It's
801 # possible to cache the content until everything is complete. Doing it this
802 # way, you can set headers everywhere.
803 #
804 # If you set a header twice, the second header will replace the first one. The
805 # header name is not casesensitive, it will allways converted in to the
806 # capitalised form suggested by the w3c (http://w3.org)
807 #
808 # === Set cookies
809 # Setting cookies is quite easy:
810 # include 'rweb'
811 #
812 # web = Rweb.new
813 # Cookie.new("Visits", web.cookies['visits'].to_i +1)
814 # web.out do
815 # web.puts "Welcome back! You visited this page #{web.cookies['visits'].to_i +1} times"
816 # end
817 #
818 # See the class Cookie for more details.
819 #
820 # === Get form and cookie values
821 # There are four ways to submit data from the browser to the server and your
822 # ruby script: via GET, POST, cookies and file upload. Rweb doesn't support
823 # file upload by now.
824 #
825 # include 'rweb'
826 #
827 # web = Rweb.new
828 # web.out do
829 # web.print "action: #{web.get['action']} "
830 # web.puts "The value of the cookie 'visits' is #{web.cookies['visits']}"
831 # web.puts "The post parameter 'test['x']' is #{web.post['test']['x']}"
832 # end
833
834 RWEB_VERSION = "0.1.0"
835 RWEB = "rweb/#{RWEB_VERSION}"
836
837 #require 'rwebcookie' -> edit by bunny :-)
838
839 class Rweb
840 # All parameter submitted via the GET method are available in attribute
841 # get. This is Hash, where every parameter is available as a key-value
842 # pair.
843 #
844 # If your input tag has a name like this one, it's value will be available
845 # as web.get["fieldname"]
846 # <input name="fieldname">
847 # You can submit values as a Hash
848 # <input name="text['index']">
849 # <input name="text['index2']">
850 # will be available as
851 # web.get["text"]["index"]
852 # web.get["text"]["index2"]
853 # Integers are also possible
854 # <input name="int[2]">
855 # <input name="int[3]['hi']>
856 # will be available as
857 # web.get["int"][2]
858 # web.get["int"][3]["hi"]
859 # If you specify no index, the lowest unused index will be used:
860 # <input name="int[]"><!-- First Field -->
861 # <input name="int[]"><!-- Second one -->
862 # will be available as
863 # web.get["int"][0] # First Field
864 # web.get["int"][1] # Second one
865 # Please notice, this doesn'd work like you might expect:
866 # <input name="text[index]">
867 # It will not be available as web.get["text"]["index"] but
868 # web.get["text[index]"]
869 attr_reader :get
870
871 # All parameters submitted via POST are available in the attribute post. It
872 # works like the get attribute.
873 # <input name="text[0]">
874 # will be available as
875 # web.post["text"][0]
876 attr_reader :post
877
878 # All cookies submitted by the browser are available in cookies. This is a
879 # Hash, where every cookie is a key-value pair.
880 attr_reader :cookies
881
882 # The name of the browser identification is submitted as USER_AGENT and
883 # available in this attribute.
884 attr_reader :user_agent
885
886 # The IP address of the client.
887 attr_reader :remote_addr
888
889 # Creates a new Rweb object. This should only done once. You can set various
890 # options via the settings hash.
891 #
892 # "cache" => true: Everything you script send to the client will be cached
893 # until the end of the out block or until flush is called. This way, you
894 # can modify headers and cookies even after printing something to the client.
895 #
896 # "safe" => level: Changes the $SAFE attribute. By default, $SAFE will be set
897 # to 1. If $SAFE is already higher than this value, it won't be changed.
898 #
899 # "silend" => true: Normaly, Rweb adds automaticly a header like this
900 # "X-Powered-By: Rweb/x.x.x (Ruby/y.y.y)". With the silend option you can
901 # suppress this.
902 def initialize (settings = {})
903 # {{{
904 @header = {}
905 @cookies = {}
906 @get = {}
907 @post = {}
908
909 # Internal attributes
910 @status = nil
911 @reasonPhrase = nil
912 @setcookies = []
913 @output_started = false;
914 @output_allowed = false;
915
916 @mod_ruby = false
917 @env = ENV.to_hash
918
919 if defined?(MOD_RUBY)
920 @output_method = "mod_ruby"
921 @mod_ruby = true
922 elsif @env['SERVER_SOFTWARE'] =~ /^Microsoft-IIS/i
923 @output_method = "nph"
924 else
925 @output_method = "ph"
926 end
927
928 unless settings.is_a?(Hash)
929 raise TypeError, "settings must be a Hash"
930 end
931 @settings = settings
932
933 unless @settings.has_key?("safe")
934 @settings["safe"] = 1
935 end
936
937 if $SAFE < @settings["safe"]
938 $SAFE = @settings["safe"]
939 end
940
941 unless @settings.has_key?("cache")
942 @settings["cache"] = false
943 end
944
945 # mod_ruby sets no QUERY_STRING variable, if no GET-Parameters are given
946 unless @env.has_key?("QUERY_STRING")
947 @env["QUERY_STRING"] = ""
948 end
949
950 # Now we split the QUERY_STRING by the seperators & and ; or, if
951 # specified, settings['get seperator']
952 unless @settings.has_key?("get seperator")
953 get_args = @env['QUERY_STRING'].split(/[&;]/)
954 else
955 get_args = @env['QUERY_STRING'].split(@settings['get seperator'])
956 end
957
958 get_args.each do | arg |
959 arg_key, arg_val = arg.split(/=/, 2)
960 arg_key = Rweb::unescape(arg_key)
961 arg_val = Rweb::unescape(arg_val)
962
963 # Parse names like name[0], name['text'] or name[]
964 pattern = /^(.+)\[("[^\]]*"|'[^\]]*'|[0-9]*)\]$/
965 keys = []
966 while match = pattern.match(arg_key)
967 arg_key = match[1]
968 keys = [match[2]] + keys
969 end
970 keys = [arg_key] + keys
971
972 akt = @get
973 last = nil
974 lastkey = nil
975 keys.each do |key|
976 if key == ""
977 # No key specified (like in "test[]"), so we use the
978 # lowerst unused Integer as key
979 key = 0
980 while akt.has_key?(key)
981 key += 1
982 end
983 elsif /^[0-9]*$/ =~ key
984 # If the index is numerical convert it to an Integer
985 key = key.to_i
986 elsif key[0].chr == "'" || key[0].chr == '"'
987 key = key[1, key.length() -2]
988 end
989 if !akt.has_key?(key) || !akt[key].class == Hash
990 # create an empty Hash if there isn't already one
991 akt[key] = {}
992 end
993 last = akt
994 lastkey = key
995 akt = akt[key]
996 end
997 last[lastkey] = arg_val
998 end
999
1000 if @env['REQUEST_METHOD'] == "POST"
1001 if @env.has_key?("CONTENT_TYPE") && @env['CONTENT_TYPE'] == "application/x-www-form-urlencoded" && @env.has_key?('CONTENT_LENGTH')
1002 unless @settings.has_key?("post seperator")
1003 post_args = $stdin.read(@env['CONTENT_LENGTH'].to_i).split(/[&;]/)
1004 else
1005 post_args = $stdin.read(@env['CONTENT_LENGTH'].to_i).split(@settings['post seperator'])
1006 end
1007 post_args.each do | arg |
1008 arg_key, arg_val = arg.split(/=/, 2)
1009 arg_key = Rweb::unescape(arg_key)
1010 arg_val = Rweb::unescape(arg_val)
1011
1012 # Parse names like name[0], name['text'] or name[]
1013 pattern = /^(.+)\[("[^\]]*"|'[^\]]*'|[0-9]*)\]$/
1014 keys = []
1015 while match = pattern.match(arg_key)
1016 arg_key = match[1]
1017 keys = [match[2]] + keys
1018 end
1019 keys = [arg_key] + keys
1020
1021 akt = @post
1022 last = nil
1023 lastkey = nil
1024 keys.each do |key|
1025 if key == ""
1026 # No key specified (like in "test[]"), so we use
1027 # the lowerst unused Integer as key
1028 key = 0
1029 while akt.has_key?(key)
1030 key += 1
1031 end
1032 elsif /^[0-9]*$/ =~ key
1033 # If the index is numerical convert it to an Integer
1034 key = key.to_i
1035 elsif key[0].chr == "'" || key[0].chr == '"'
1036 key = key[1, key.length() -2]
1037 end
1038 if !akt.has_key?(key) || !akt[key].class == Hash
1039 # create an empty Hash if there isn't already one
1040 akt[key] = {}
1041 end
1042 last = akt
1043 lastkey = key
1044 akt = akt[key]
1045 end
1046 last[lastkey] = arg_val
1047 end
1048 else
1049 # Maybe we should print a warning here?
1050 $stderr.print("Unidentified form data recived and discarded.")
1051 end
1052 end
1053
1054 if @env.has_key?("HTTP_COOKIE")
1055 cookie = @env['HTTP_COOKIE'].split(/; ?/)
1056 cookie.each do | c |
1057 cookie_key, cookie_val = c.split(/=/, 2)
1058
1059 @cookies [Rweb::unescape(cookie_key)] = Rweb::unescape(cookie_val)
1060 end
1061 end
1062
1063 if defined?(@env['HTTP_USER_AGENT'])
1064 @user_agent = @env['HTTP_USER_AGENT']
1065 else
1066 @user_agent = nil;
1067 end
1068
1069 if defined?(@env['REMOTE_ADDR'])
1070 @remote_addr = @env['REMOTE_ADDR']
1071 else
1072 @remote_addr = nil
1073 end
1074 # }}}
1075 end
1076
1077 # Prints a String to the client. If caching is enabled, the String will
1078 # buffered until the end of the out block ends.
1079 def print(str = "")
1080 # {{{
1081 unless @output_allowed
1082 raise "You just can write to output inside of a Rweb::out-block"
1083 end
1084
1085 if @settings["cache"]
1086 @buffer += [str.to_s]
1087 else
1088 unless @output_started
1089 sendHeaders
1090 end
1091 $stdout.print(str)
1092 end
1093 nil
1094 # }}}
1095 end
1096
1097 # Prints a String to the client and adds a line break at the end. Please
1098 # remember, that a line break is not visible in HTML, use the <br> HTML-Tag
1099 # for this. If caching is enabled, the String will buffered until the end
1100 # of the out block ends.
1101 def puts(str = "")
1102 # {{{
1103 self.print(str + "\n")
1104 # }}}
1105 end
1106
1107 # Alias to print.
1108 def write(str = "")
1109 # {{{
1110 self.print(str)
1111 # }}}
1112 end
1113
1114 # If caching is enabled, all cached data are send to the cliend and the
1115 # cache emptied.
1116 def flush
1117 # {{{
1118 unless @output_allowed
1119 raise "You can't use flush outside of a Rweb::out-block"
1120 end
1121 buffer = @buffer.join
1122
1123 unless @output_started
1124 sendHeaders
1125 end
1126 $stdout.print(buffer)
1127
1128 @buffer = []
1129 # }}}
1130 end
1131
1132 # Sends one or more header to the client. All headers are cached just
1133 # before body data are send to the client. If the same header are set
1134 # twice, only the last value is send.
1135 #
1136 # Example:
1137 # web.header("Last-Modified: Mon, 16 Feb 2004 20:15:41 GMT")
1138 # web.header("Location: http://www.ruby-lang.org")
1139 #
1140 # You can specify more than one header at the time by doing something like
1141 # this:
1142 # web.header("Content-Type: text/plain\nContent-Length: 383")
1143 # or
1144 # web.header(["Content-Type: text/plain", "Content-Length: 383"])
1145 def header(str)
1146 # {{{
1147 if @output_started
1148 raise "HTTP-Headers are already send. You can't change them after output has started!"
1149 end
1150 unless @output_allowed
1151 raise "You just can set headers inside of a Rweb::out-block"
1152 end
1153 if str.is_a?Array
1154 str.each do | value |
1155 self.header(value)
1156 end
1157
1158 elsif str.split(/\n/).length > 1
1159 str.split(/\n/).each do | value |
1160 self.header(value)
1161 end
1162
1163 elsif str.is_a? String
1164 str.gsub!(/\r/, "")
1165
1166 if (str =~ /^HTTP\/1\.[01] [0-9]{3} ?.*$/) == 0
1167 pattern = /^HTTP\/1.[01] ([0-9]{3}) ?(.*)$/
1168
1169 result = pattern.match(str)
1170 self.setstatus(result[0], result[1])
1171 elsif (str =~ /^status: [0-9]{3} ?.*$/i) == 0
1172 pattern = /^status: ([0-9]{3}) ?(.*)$/i
1173
1174 result = pattern.match(str)
1175 self.setstatus(result[0], result[1])
1176 else
1177 a = str.split(/: ?/, 2)
1178
1179 @header[a[0].downcase] = a[1]
1180 end
1181 end
1182 # }}}
1183 end
1184
1185 # Changes the status of this page. There are several codes like "200 OK",
1186 # "302 Found", "404 Not Found" or "500 Internal Server Error". A list of
1187 # all codes is available at
1188 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
1189 #
1190 # You can just send the code number, the reason phrase will be added
1191 # automaticly with the recommendations from the w3c if not specified. If
1192 # you set the status twice or more, only the last status will be send.
1193 # Examples:
1194 # web.status("401 Unauthorized")
1195 # web.status("410 Sad but true, this lonely page is gone :(")
1196 # web.status(206)
1197 # web.status("400")
1198 #
1199 # The default status is "200 OK". If a "Location" header is set, the
1200 # default status is "302 Found".
1201 def status(str)
1202 # {{{
1203 if @output_started
1204 raise "HTTP-Headers are already send. You can't change them after output has started!"
1205 end
1206 unless @output_allowed
1207 raise "You just can set headers inside of a Rweb::out-block"
1208 end
1209 if str.is_a?Integer
1210 @status = str
1211 elsif str.is_a?String
1212 p1 = /^([0-9]{3}) ?(.*)$/
1213 p2 = /^HTTP\/1\.[01] ([0-9]{3}) ?(.*)$/
1214 p3 = /^status: ([0-9]{3}) ?(.*)$/i
1215
1216 if (a = p1.match(str)) == nil
1217 if (a = p2.match(str)) == nil
1218 if (a = p3.match(str)) == nil
1219 raise ArgumentError, "Invalid argument", caller
1220 end
1221 end
1222 end
1223 @status = a[1].to_i
1224 if a[2] != ""
1225 @reasonPhrase = a[2]
1226 else
1227 @reasonPhrase = getReasonPhrase(@status)
1228 end
1229 else
1230 raise ArgumentError, "Argument of setstatus must be integer or string", caller
1231 end
1232 # }}}
1233 end
1234
1235 # Handles the output of your content and rescues all exceptions. Send all
1236 # data in the block to this method. For example:
1237 # web.out do
1238 # web.header("Content-Type: text/plain")
1239 # web.puts("Hello, plain world!")
1240 # end
1241 def out
1242 # {{{
1243 @output_allowed = true
1244 @buffer = []; # We use an array as buffer, because it's more performant :)
1245
1246 begin
1247 yield
1248 rescue Exception => exception
1249 $stderr.puts "Ruby exception rescued (#{exception.class}): #{exception.message}"
1250 $stderr.puts exception.backtrace.join("\n")
1251
1252 unless @output_started
1253 self.setstatus(500)
1254 @header = {}
1255 end
1256
1257 unless (@settings.has_key?("hide errors") and @settings["hide errors"] == true)
1258 unless @output_started
1259 self.header("Content-Type: text/html")
1260 self.puts "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Strict//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"
1261 self.puts "<html>"
1262 self.puts "<head>"
1263 self.puts "<title>500 Internal Server Error</title>"
1264 self.puts "</head>"
1265 self.puts "<body>"
1266 end
1267 if @header.has_key?("content-type") and (@header["content-type"] =~ /^text\/html/i) == 0
1268 self.puts "<h1>Internal Server Error</h1>"
1269 self.puts "<p>The server encountered an exception and was unable to complete your request.</p>"
1270 self.puts "<p>The exception has provided the following information:</p>"
1271 self.puts "<pre style=\"background: #FFCCCC; border: black solid 2px; margin-left: 2cm; margin-right: 2cm; padding: 2mm;\"><b>#{exception.class}</b>: #{exception.message} <b>on</b>"
1272 self.puts
1273 self.puts "#{exception.backtrace.join("\n")}</pre>"
1274 self.puts "</body>"
1275 self.puts "</html>"
1276 else
1277 self.puts "The server encountered an exception and was unable to complete your request"
1278 self.puts "The exception has provided the following information:"
1279 self.puts "#{exception.class}: #{exception.message}"
1280 self.puts
1281 self.puts exception.backtrace.join("\n")
1282 end
1283 end
1284 end
1285
1286 if @settings["cache"]
1287 buffer = @buffer.join
1288
1289 unless @output_started
1290 unless @header.has_key?("content-length")
1291 self.header("content-length: #{buffer.length}")
1292 end
1293
1294 sendHeaders
1295 end
1296 $stdout.print(buffer)
1297 elsif !@output_started
1298 sendHeaders
1299 end
1300 @output_allowed = false;
1301 # }}}
1302 end
1303
1304 # Decodes URL encoded data, %20 for example stands for a space.
1305 def Rweb.unescape(str)
1306 # {{{
1307 if defined? str and str.is_a? String
1308 str.gsub!(/\+/, " ")
1309 str.gsub(/%.{2}/) do | s |
1310 s[1,2].hex.chr
1311 end
1312 end
1313 # }}}
1314 end
1315
1316 protected
1317 def sendHeaders
1318 # {{{
1319
1320 Cookie.disallow # no more cookies can be set or modified
1321 if !(@settings.has_key?("silent") and @settings["silent"] == true) and [email protected]_key?("x-powered-by")
1322 if @mod_ruby
1323 header("x-powered-by: #{RWEB} (Ruby/#{RUBY_VERSION}, #{MOD_RUBY})");
1324 else
1325 header("x-powered-by: #{RWEB} (Ruby/#{RUBY_VERSION})");
1326 end
1327 end
1328
1329 if @output_method == "ph"
1330 if ((@status == nil or @status == 200) and [email protected]_key?("content-type") and [email protected]_key?("location"))
1331 header("content-type: text/html")
1332 end
1333
1334 if @status != nil
1335 $stdout.print "Status: #{@status} #{@reasonPhrase}\r\n"
1336 end
1337
1338 @header.each do |key, value|
1339 key = key *1 # "unfreeze" key :)
1340 key[0] = key[0,1].upcase![0]
1341
1342 key = key.gsub(/-[a-z]/) do |char|
1343 "-" + char[1,1].upcase
1344 end
1345
1346 $stdout.print "#{key}: #{value}\r\n"
1347 end
1348 cookies = Cookie.getHttpHeader # Get all cookies as an HTTP Header
1349 if cookies
1350 $stdout.print cookies
1351 end
1352
1353 $stdout.print "\r\n"
1354
1355 elsif @output_method == "nph"
1356 elsif @output_method == "mod_ruby"
1357 r = Apache.request
1358
1359 if ((@status == nil or @status == 200) and [email protected]_key?("content-type") and [email protected]_key?("location"))
1360 header("text/html")
1361 end
1362
1363 if @status != nil
1364 r.status_line = "#{@status} #{@reasonPhrase}"
1365 end
1366
1367 r.send_http_header
1368 @header.each do |key, value|
1369 key = key *1 # "unfreeze" key :)
1370
1371 key[0] = key[0,1].upcase![0]
1372 key = key.gsub(/-[a-z]/) do |char|
1373 "-" + char[1,1].upcase
1374 end
1375 puts "#{key}: #{value.class}"
1376 #r.headers_out[key] = value
1377 end
1378 end
1379 @output_started = true
1380 # }}}
1381 end
1382
1383 def getReasonPhrase (status)
1384 # {{{
1385 if status == 100
1386 "Continue"
1387 elsif status == 101
1388 "Switching Protocols"
1389 elsif status == 200
1390 "OK"
1391 elsif status == 201
1392 "Created"
1393 elsif status == 202
1394 "Accepted"
1395 elsif status == 203
1396 "Non-Authoritative Information"
1397 elsif status == 204
1398 "No Content"
1399 elsif status == 205
1400 "Reset Content"
1401 elsif status == 206
1402 "Partial Content"
1403 elsif status == 300
1404 "Multiple Choices"
1405 elsif status == 301
1406 "Moved Permanently"
1407 elsif status == 302
1408 "Found"
1409 elsif status == 303
1410 "See Other"
1411 elsif status == 304
1412 "Not Modified"
1413 elsif status == 305
1414 "Use Proxy"
1415 elsif status == 307
1416 "Temporary Redirect"
1417 elsif status == 400
1418 "Bad Request"
1419 elsif status == 401
1420 "Unauthorized"
1421 elsif status == 402
1422 "Payment Required"
1423 elsif status == 403
1424 "Forbidden"
1425 elsif status == 404
1426 "Not Found"
1427 elsif status == 405
1428 "Method Not Allowed"
1429 elsif status == 406
1430 "Not Acceptable"
1431 elsif status == 407
1432 "Proxy Authentication Required"
1433 elsif status == 408
1434 "Request Time-out"
1435 elsif status == 409
1436 "Conflict"
1437 elsif status == 410
1438 "Gone"
1439 elsif status == 411
1440 "Length Required"
1441 elsif status == 412
1442 "Precondition Failed"
1443 elsif status == 413
1444 "Request Entity Too Large"
1445 elsif status == 414
1446 "Request-URI Too Large"
1447 elsif status == 415
1448 "Unsupported Media Type"
1449 elsif status == 416
1450 "Requested range not satisfiable"
1451 elsif status == 417
1452 "Expectation Failed"
1453 elsif status == 500
1454 "Internal Server Error"
1455 elsif status == 501
1456 "Not Implemented"
1457 elsif status == 502
1458 "Bad Gateway"
1459 elsif status == 503
1460 "Service Unavailable"
1461 elsif status == 504
1462 "Gateway Time-out"
1463 elsif status == 505
1464 "HTTP Version not supported"
1465 else
1466 raise "Unknown Statuscode. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1 for more information."
1467 end
1468 # }}}
1469 end
1470 end
1471
1472 class Cookie
1473 attr_reader :name, :value, :maxage, :path, :domain, :secure, :comment
1474
1475 # Sets a cookie. Please see below for details of the attributes.
1476 def initialize (name, value = nil, maxage = nil, path = nil, domain = nil, secure = false)
1477 # {{{
1478 # HTTP headers (Cookies are a HTTP header) can only set, while no content
1479 # is send. So an exception will be raised, when @@allowed is set to false
1480 # and a new cookie has set.
1481 unless defined?(@@allowed)
1482 @@allowed = true
1483 end
1484 unless @@allowed
1485 raise "You can't set cookies after the HTTP headers are send."
1486 end
1487
1488 unless defined?(@@list)
1489 @@list = []
1490 end
1491 @@list += [self]
1492
1493 unless defined?(@@type)
1494 @@type = "netscape"
1495 end
1496
1497 unless name.class == String
1498 raise TypeError, "The name of a cookie must be a string", caller
1499 end
1500 if value.class.superclass == Integer || value.class == Float
1501 value = value.to_s
1502 elsif value.class != String && value != nil
1503 raise TypeError, "The value of a cookie must be a string, integer, float or nil", caller
1504 end
1505 if maxage.class == Time
1506 maxage = maxage - Time.now
1507 elsif !maxage.class.superclass == Integer || !maxage == nil
1508 raise TypeError, "The maxage date of a cookie must be an Integer or Time object or nil.", caller
1509 end
1510 unless path.class == String || path == nil
1511 raise TypeError, "The path of a cookie must be nil or a string", caller
1512 end
1513 unless domain.class == String || domain == nil
1514 raise TypeError, "The value of a cookie must be nil or a string", caller
1515 end
1516 unless secure == true || secure == false
1517 raise TypeError, "The secure field of a cookie must be true or false", caller
1518 end
1519
1520 @name, @value, @maxage, @path, @domain, @secure = name, value, maxage, path, domain, secure
1521 @comment = nil
1522 # }}}
1523 end
1524
1525 # Modifies the value of this cookie. The information you want to store. If the
1526 # value is nil, the cookie will be deleted by the client.
1527 #
1528 # This attribute can be a String, Integer or Float object or nil.
1529 def value=(value)
1530 # {{{
1531 if value.class.superclass == Integer || value.class == Float
1532 value = value.to_s
1533 elsif value.class != String && value != nil
1534 raise TypeError, "The value of a cookie must be a string, integer, float or nil", caller
1535 end
1536 @value = value
1537 # }}}
1538 end
1539
1540 # Modifies the maxage of this cookie. This attribute defines the lifetime of
1541 # the cookie, in seconds. A value of 0 means the cookie should be discarded
1542 # imediatly. If it set to nil, the cookie will be deleted when the browser
1543 # will be closed.
1544 #
1545 # Attention: This is different from other implementations like PHP, where you
1546 # gives the seconds since 1/1/1970 0:00:00 GMT.
1547 #
1548 # This attribute must be an Integer or Time object or nil.
1549 def maxage=(maxage)
1550 # {{{
1551 if maxage.class == Time
1552 maxage = maxage - Time.now
1553 elsif maxage.class.superclass == Integer || !maxage == nil
1554 raise TypeError, "The maxage of a cookie must be an Interger or Time object or nil.", caller
1555 end
1556 @maxage = maxage
1557 # }}}
1558 end
1559
1560 # Modifies the path value of this cookie. The client will send this cookie
1561 # only, if the requested document is this directory or a subdirectory of it.
1562 #
1563 # The value of the attribute must be a String object or nil.
1564 def path=(path)
1565 # {{{
1566 unless path.class == String || path == nil
1567 raise TypeError, "The path of a cookie must be nil or a string", caller
1568 end
1569 @path = path
1570 # }}}
1571 end
1572
1573 # Modifies the domain value of this cookie. The client will send this cookie
1574 # only if it's connected with this domain (or a subdomain, if the first
1575 # character is a dot like in ".ruby-lang.org")
1576 #
1577 # The value of this attribute must be a String or nil.
1578 def domain=(domain)
1579 # {{{
1580 unless domain.class == String || domain == nil
1581 raise TypeError, "The domain of a cookie must be a String or nil.", caller
1582 end
1583 @domain = domain
1584 # }}}
1585 end
1586
1587 # Modifies the secure flag of this cookie. If it's true, the client will only
1588 # send this cookie if it is secured connected with us.
1589 #
1590 # The value od this attribute has to be true or false.
1591 def secure=(secure)
1592 # {{{
1593 unless secure == true || secure == false
1594 raise TypeError, "The secure field of a cookie must be true or false", caller
1595 end
1596 @secure = secure
1597 # }}}
1598 end
1599
1600 # Modifies the comment value of this cookie. The comment won't be send, if
1601 # type is "netscape".
1602 def comment=(comment)
1603 # {{{
1604 unless comment.class == String || comment == nil
1605 raise TypeError, "The comment of a cookie must be a string or nil", caller
1606 end
1607 @comment = comment
1608 # }}}
1609 end
1610
1611 # Changes the type of all cookies.
1612 # Allowed values are RFC2109 and netscape (default).
1613 def Cookie.type=(type)
1614 # {{{
1615 unless @@allowed
1616 raise "The cookies are allready send, so you can't change the type anymore."
1617 end
1618 unless type.downcase == "rfc2109" && type.downcase == "netscape"
1619 raise "The type of the cookies must be \"RFC2109\" or \"netscape\"."
1620 end
1621 @@type = type;
1622 # }}}
1623 end
1624
1625 # After sending this message, no cookies can be set or modified. Use it, when
1626 # HTTP-Headers are send. Rweb does this for you.
1627 def Cookie.disallow
1628 # {{{
1629 @@allowed = false
1630 true
1631 # }}}
1632 end
1633
1634 # Returns a HTTP header (type String) with all cookies. Rweb does this for
1635 # you.
1636 def Cookie.getHttpHeader
1637 # {{{
1638 if defined?(@@list)
1639 if @@type == "netscape"
1640 str = ""
1641 @@list.each do |cookie|
1642 if cookie.value == nil
1643 cookie.maxage = 0
1644 cookie.value = ""
1645 end
1646 # TODO: Name and value should be escaped!
1647 str += "Set-Cookie: #{cookie.name}=#{cookie.value}"
1648 unless cookie.maxage == nil
1649 expire = Time.now + cookie.maxage
1650 expire.gmtime
1651 str += "; Expire=#{expire.strftime("%a, %d-%b-%Y %H:%M:%S %Z")}"
1652 end
1653 unless cookie.domain == nil
1654 str += "; Domain=#{cookie.domain}"
1655 end
1656 unless cookie.path == nil
1657 str += "; Path=#{cookie.path}"
1658 end
1659 if cookie.secure
1660 str += "; Secure"
1661 end
1662 str += "\r\n"
1663 end
1664 return str
1665 else # type == "RFC2109"
1666 str = "Set-Cookie: "
1667 comma = false;
1668
1669 @@list.each do |cookie|
1670 if cookie.value == nil
1671 cookie.maxage = 0
1672 cookie.value = ""
1673 end
1674 if comma
1675 str += ","
1676 end
1677 comma = true
1678
1679 str += "#{cookie.name}=\"#{cookie.value}\""
1680 unless cookie.maxage == nil
1681 str += "; Max-Age=\"#{cookie.maxage}\""
1682 end
1683 unless cookie.domain == nil
1684 str += "; Domain=\"#{cookie.domain}\""
1685 end
1686 unless cookie.path == nil
1687 str += "; Path=\"#{cookie.path}\""
1688 end
1689 if cookie.secure
1690 str += "; Secure"
1691 end
1692 unless cookie.comment == nil
1693 str += "; Comment=\"#{cookie.comment}\""
1694 end
1695 str += "; Version=\"1\""
1696 end
1697 str
1698 end
1699 else
1700 false
1701 end
1702 # }}}
1703 end
1704 end
1705
1706 require 'strscan'
1707
1708 module BBCode
1709 DEBUG = true
1710
1711 use 'encoder', 'tags', 'tagstack', 'smileys'
1712
1713 =begin
1714 The Parser class takes care of the encoding.
1715 It scans the given BBCode (as plain text), finds tags
1716 and smilies and also makes links of urls in text.
1717
1718 Normal text is send directly to the encoder.
1719
1720 If a tag was found, an instance of a Tag subclass is created
1721 to handle the case.
1722
1723 The @tagstack manages tag nesting and ensures valid HTML.
1724 =end
1725
1726 class Parser
1727 class Attribute
1728 # flatten and use only one empty_arg
1729 def self.create attr
1730 attr = flatten attr
1731 return @@empty_attr if attr.empty?
1732 new attr
1733 end
1734
1735 private_class_method :new
1736
1737 # remove leading and trailing whitespace; concat lines
1738 def self.flatten attr
1739 attr.strip.gsub(/\n/, ' ')
1740 # -> ^ and $ can only match at begin and end now
1741 end
1742
1743 ATTRIBUTE_SCAN = /
1744 (?!$) # don't match at end
1745 \s*
1746 ( # $1 = key
1747 [^=\s\]"\\]*
1748 (?:
1749 (?: \\. | "[^"\\]*(?:\\.[^"\\]*)*"? )
1750 [^=\s\]"\\]*
1751 )*
1752 )
1753 (?:
1754 =
1755 ( # $2 = value
1756 [^\s\]"\\]*
1757 (?:
1758 (?: \\. | "[^"\\]*(?:\\.[^"\\]*)*"? )
1759 [^\s\]"\\]*
1760 )*
1761 )?
1762 )?
1763 \s*
1764 /x
1765
1766 def self.parse source
1767 source = source.dup
1768 # empty_tag: the tag looks like [... /]
1769 # slice!: this deletes the \s*/] at the end
1770 # \s+ because [url=http://rubybb.org/forum/] is NOT an empty tag.
1771 # In RubyBBCode, you can use [url=http://rubybb.org/forum/ /], and this has to be
1772 # interpreted correctly.
1773 empty_tag = source.sub!(/^:/, '=') or source.slice!(/\/$/)
1774 debug 'PARSE: ' + source.inspect + ' => ' + empty_tag.inspect
1775 #-> we have now an attr that's EITHER empty OR begins and ends with non-whitespace.
1776
1777 attr = Hash.new
1778 attr[:flags] = []
1779 source.scan(ATTRIBUTE_SCAN) { |key, value|
1780 if not value
1781 attr[:flags] << unescape(key)
1782 else
1783 next if value.empty? and key.empty?
1784 attr[unescape(key)] = unescape(value)
1785 end
1786 }
1787 debug attr.inspect
1788
1789 return empty_tag, attr
1790 end
1791
1792 def self.unescape_char esc
1793 esc[1]
1794 end
1795
1796 def self.unquote qt
1797 qt[1..-1].chomp('"').gsub(/\\./) { |esc| unescape_char esc }
1798 end
1799
1800 def self.unescape str
1801 str.gsub(/ (\\.) | (" [^"\\]* (?:\\.[^"\\]*)* "?) /x) {
1802 if $1
1803 unescape_char $1
1804 else
1805 unquote $2
1806 end
1807 }
1808 end
1809
1810 include Enumerable
1811 def each &block
1812 @args.each(&block)
1813 end
1814
1815 attr_reader :source, :args, :value
1816
1817 def initialize source
1818 @source = source
1819 debug 'Attribute#new(%p)' % source
1820 @empty_tag, @attr = Attribute.parse source
1821 @value = @attr[''].to_s
1822 end
1823
1824 def empty?
1825 self == @@empty_attr
1826 end
1827
1828 def empty_tag?
1829 @empty_tag
1830 end
1831
1832 def [] *keys
1833 res = @attr[*keys]
1834 end
1835
1836 def flags
1837 attr[:flags]
1838 end
1839
1840 def to_s
1841 @attr
1842 end
1843
1844 def inspect
1845 'ATTR[' + @attr.inspect + (@empty_tag ? ' | empty tag' : '') + ']'
1846 end
1847 end
1848 class Attribute
1849 @@empty_attr = new ''
1850 end
1851 end
1852
1853 class Parser
1854 def Parser.flatten str
1855 # replace mac & dos newlines with unix style
1856 str.gsub(/\r\n?/, "\n")
1857 end
1858
1859 def initialize input = ''
1860 # input manager
1861 @scanner = StringScanner.new ''
1862 # output manager
1863 @encoder = Encoder.new
1864 @output = ''
1865 # tag manager
1866 @tagstack = TagStack.new(@encoder)
1867
1868 @do_magic = true
1869 # set the input
1870 feed input
1871 end
1872
1873 # if you want, you can feed a parser instance after creating,
1874 # or even feed it repeatedly.
1875 def feed food
1876 @scanner.string = Parser.flatten food
1877 end
1878
1879 # parse through the string using parse_token
1880 def parse
1881 parse_token until @scanner.eos?
1882 @tagstack.close_all
1883 @output = parse_magic @encoder.output
1884 end
1885
1886 def output
1887 @output
1888 end
1889
1890 # ok, internals start here
1891 private
1892 # the default output functions. everything should use them or the tags.
1893 def add_text text = @scanner.matched
1894 @encoder.add_text text
1895 end
1896
1897 # use this carefully
1898 def add_html html
1899 @encoder.add_html html
1900 end
1901
1902 # highlights the text as error
1903 def add_garbage garbage
1904 add_html '<span class="error">' if DEBUG
1905 add_text garbage
1906 add_html '</span>' if DEBUG
1907 end
1908
1909 # unknown and incorrectly nested tags are ignored and
1910 # sent as plaintext (garbage in - garbage out).
1911 # in debug mode, garbage is marked with lime background.
1912 def garbage_out start
1913 @scanner.pos = start
1914 garbage = @scanner.scan(/./m)
1915 debug 'GARBAGE: ' + garbage
1916 add_garbage garbage
1917 end
1918
1919 # simple text; everything but [, \[ allowed
1920 SIMPLE_TEXT_SCAN_ = /
1921 [^\[\\]* # normal*
1922 (?: # (
1923 \\.? # special
1924 [^\[\\]* # normal*
1925 )* # )*
1926 /mx
1927 SIMPLE_TEXT_SCAN = /[^\[]+/
1928
1929 =begin
1930
1931 WHAT IS A TAG?
1932 ==============
1933
1934 Tags in BBCode can be much more than just a simple [b].
1935 I use many terms here to differ the parts of each tag.
1936
1937 Basic scheme:
1938 [ code ]
1939 TAG START TAG INFO TAG END
1940
1941 Most tags need a second tag to close the range it opened.
1942 This is done with CLOSING TAGS:
1943 [/code]
1944 or by using empty tags that have no content and close themselfes:
1945 [url=winamp.com /]
1946 You surely know this from HTML.
1947 These slashes define the TAG KIND = normal|closing|empty and
1948 cannot be used together.
1949
1950 Everything between [ and ] and expluding the slashes is called the
1951 TAG INFO. This info may contain:
1952 - TAG ID
1953 - TAG NAME including the tag id
1954 - attributes
1955
1956 The TAG ID is the first char of the info:
1957
1958 TAG | ID
1959 ----------+----
1960 [quote] | q
1961 [&plusmn] | &
1962 ["[b]"] | "
1963 [/url] | u
1964 [---] | -
1965
1966 As you can see, the tag id shows the TAG TYPE, it can be a
1967 normal tag, a formatting tag or an entity.
1968 Therefor, the parser first scans the id to decide how to go
1969 on with parsing.
1970 =end
1971 # tag
1972 # TODO more complex expression allowing
1973 # [quote="[ladico]"] and [quote=\[ladico\]] to be correct tags
1974 TAG_BEGIN_SCAN = /
1975 \[ # tag start
1976 ( \/ )? # $1 = closing tag?
1977 ( [^\]] ) # $2 = tag id
1978 /x
1979 TAG_END_SCAN = /
1980 [^\]]* # rest that was not handled
1981 \]? # tag end
1982 /x
1983 CLOSE_TAG_SCAN = /
1984 ( [^\]]* ) # $1 = the rest of the tag info
1985 ( \/ )? # $2 = empty tag?
1986 \]? # tag end
1987 /x
1988 UNCLOSED_TAG_SCAN = / \[ /x
1989
1990 CLASSIC_TAG_SCAN = / [a-z]* /ix
1991
1992 SEPARATOR_TAG_SCAN = / \** /x
1993
1994 FORMAT_TAG_SCAN = / -- -* /x
1995
1996 QUOTED_SCAN = /
1997 ( # $1 = quoted text
1998 [^"\\]* # normal*
1999 (?: # (
2000 \\. # special
2001 [^"\\]* # normal*
2002 )* # )*
2003 )
2004 "? # end quote "
2005 /mx
2006
2007 ENTITY_SCAN = /
2008 ( [^;\]]+ ) # $1 = entity code
2009 ;? # optional ending semicolon
2010 /ix
2011
2012 SMILEY_SCAN = Smileys::SMILEY_PATTERN
2013
2014 # this is the main parser loop that separates
2015 # text - everything until "["
2016 # from
2017 # tags - starting with "[", ending with "]"
2018 def parse_token
2019 if @scanner.scan(SIMPLE_TEXT_SCAN)
2020 add_text
2021 else
2022 handle_tag
2023 end
2024 end
2025
2026 def handle_tag
2027 tag_start = @scanner.pos
2028
2029 unless @scanner.scan TAG_BEGIN_SCAN
2030 garbage_out tag_start
2031 return
2032 end
2033
2034 closing, id = @scanner[1], @scanner[2]
2035 #debug 'handle_tag(%p)' % @scanner.matched
2036
2037 handled =
2038 case id
2039
2040 when /[a-z]/i
2041 if @scanner.scan(CLASSIC_TAG_SCAN)
2042 if handle_classic_tag(id + @scanner.matched, closing)
2043 already_closed = true
2044 end
2045 end
2046
2047 when '*'
2048 if @scanner.scan(SEPARATOR_TAG_SCAN)
2049 handle_asterisk tag_start, id + @scanner.matched
2050 true
2051 end
2052
2053 when '-'
2054 if @scanner.scan(FORMAT_TAG_SCAN)
2055 #format = id + @scanner.matched
2056 @encoder.add_html "\n<hr>\n"
2057 true
2058 end
2059
2060 when '"'
2061 if @scanner.scan(QUOTED_SCAN)
2062 @encoder.add_text unescape(@scanner[1])
2063 true
2064 end
2065
2066 when '&'
2067 if @scanner.scan(ENTITY_SCAN)
2068 @encoder.add_entity @scanner[1]
2069 true
2070 end
2071
2072 when Smileys::SMILEY_START_CHARSET
2073 @scanner.pos = @scanner.pos - 1 # (ungetch)
2074 if @scanner.scan(SMILEY_SCAN)
2075 @encoder.add_html Smileys.smiley_to_image(@scanner.matched)
2076 true
2077 end
2078
2079 end # case
2080
2081 return garbage_out(tag_start) unless handled
2082
2083 @scanner.scan(TAG_END_SCAN) unless already_closed
2084 end
2085
2086 ATTRIBUTES_SCAN = /
2087 (
2088 [^\]"\\]*
2089 (?:
2090 (?:
2091 \\.
2092 |
2093 "
2094 [^"\\]*
2095 (?:
2096 \\.
2097 [^"\\]*
2098 )*
2099 "?
2100 )
2101 [^\]"\\]*
2102 )*
2103 )
2104 \]?
2105 /x
2106
2107 def handle_classic_tag name, closing
2108 debug 'TAG: ' + (closing ? '/' : '') + name
2109 # flatten
2110 name.downcase!
2111 tag_class = TAG_LIST[name]
2112 return unless tag_class
2113
2114 #debug((opening ? 'OPEN ' : 'CLOSE ') + tag_class.name)
2115
2116 # create an attribute object to handle it
2117 @scanner.scan(ATTRIBUTES_SCAN)
2118 #debug name + ':' + @scanner[1]
2119 attr = Attribute.create @scanner[1]
2120 #debug 'ATTRIBUTES %p ' % attr #unless attr.empty?
2121
2122 #debug 'closing: %p; name=%s, attr=%p' % [closing, name, attr]
2123
2124 # OPEN
2125 if not closing and tag = @tagstack.try_open_class(tag_class, attr)
2126 #debug 'opening'
2127 tag.do_open @scanner
2128 # this should be done by the tag itself.
2129 if attr.empty_tag?
2130 tag.handle_empty
2131 @tagstack.close_tag
2132 elsif tag.special_content?
2133 handle_special_content(tag)
2134 @tagstack.close_tag
2135 # # ignore asterisks directly after the opening; these are phpBBCode
2136 # elsif tag.respond_to? :asterisk
2137 # debug 'SKIP ASTERISKS: ' if @scanner.skip(ASTERISK_TAGS_SCAN)
2138 end
2139
2140 # CLOSE
2141 elsif @tagstack.try_close_class(tag_class)
2142 #debug 'closing'
2143 # GARBAGE
2144 else
2145 return
2146 end
2147
2148 true
2149 end
2150
2151 def handle_asterisk tag_start, stars
2152 #debug 'ASTERISK: ' + stars.to_s
2153 # rule for asterisk tags: they belong to the last tag
2154 # that handles them. tags opened after this tag are closed.
2155 # if no open tag uses them, all are closed.
2156 tag = @tagstack.close_all_until { |tag| tag.respond_to? :asterisk }
2157 unless tag and tag.asterisk stars, @scanner
2158 garbage_out tag_start
2159 end
2160 end
2161
2162 def handle_special_content tag
2163 scanned = @scanner.scan_until(tag.closing_tag)
2164 if scanned
2165 scanned.slice!(-(@scanner.matched.size)..-1)
2166 else
2167 scanned = @scanner.scan(/.*/m).to_s
2168 end
2169 #debug 'SPECIAL CONTENT: ' + scanned
2170 tag.handle_content(scanned)
2171 end
2172
2173 def unescape text
2174 # input: correctly formatted quoted string (without the quotes)
2175 text.gsub(/\\(?:(["\\])|.)/) { $1 or $& }
2176 end
2177
2178
2179 # MAGIC FEAUTURES
2180
2181 URL_PATTERN = /(?:(?:www|ftp)\.|(?>\w{3,}):\/\/)\S+/
2182 EMAIL_PATTERN = /(?>[\w\-_.]+)@[\w\-\.]+\.\w+/
2183
2184 HAS_MAGIC = /[&@#{Smileys::SMILEY_START_CHARS}]|(?i:www|ftp)/
2185
2186 MAGIC_PATTERN = Regexp.new('(\W|^)(%s)' %
2187 [Smileys::MAGIC_SMILEY_PATTERN, URL_PATTERN, EMAIL_PATTERN].map { |pattern|
2188 pattern.to_s
2189 }.join('|') )
2190
2191 IS_SMILEY_PATTERN = Regexp.new('^%s' % Smileys::SMILEY_START_CHARSET.to_s )
2192 IS_URL_PATTERN = /^(?:(?i:www|ftp)\.|(?>\w+):\/\/)/
2193 URL_STARTS_WITH_PROTOCOL = /^\w+:\/\//
2194 IS_EMAIL_PATTERN = /^[\w\-_.]+@/
2195
2196 def to_magic text
2197 # debug MAGIC_PATTERN.to_s
2198 text.gsub!(MAGIC_PATTERN) {
2199 magic = $2
2200 $1 + case magic
2201 when IS_SMILEY_PATTERN
2202 Smileys.smiley_to_img magic
2203 when IS_URL_PATTERN
2204 last = magic.slice_punctation! # no punctation in my URL
2205 href = magic
2206 href.insert(0, 'http://') unless magic =~ URL_STARTS_WITH_PROTOCOL
2207 '<a href="' + href + '">' + magic + '</a>' + last
2208 when IS_EMAIL_PATTERN
2209 last = magic.slice_punctation!
2210 '<a href="mailto:' + magic + '">' + magic + '</a>' + last
2211 else
2212 raise '{{{' + magic + '}}}'
2213 end
2214 }
2215 text
2216 end
2217
2218 # handles smileys and urls
2219 def parse_magic html
2220 return html unless @do_magic
2221 scanner = StringScanner.new html
2222 out = ''
2223 while scanner.rest?
2224 if scanner.scan(/ < (?: a\s .*? <\/a> | pre\W .*? <\/pre> | [^>]* > ) /mx)
2225 out << scanner.matched
2226 elsif scanner.scan(/ [^<]+ /x)
2227 out << to_magic(scanner.matched)
2228
2229 # this should never happen
2230 elsif scanner.scan(/./m)
2231 raise 'ERROR: else case reached'
2232 end
2233 end
2234 out
2235 end
2236 end # Parser
2237 end
2238
2239 class String
2240 def slice_punctation!
2241 slice!(/[.:,!\?]+$/).to_s # return '' instead of nil
2242 end
2243 end
2244
2245 #
2246 # = Grammar
2247 #
2248 # An implementation of common algorithms on grammars.
2249 #
2250 # This is used by Shinobu, a visualization tool for educating compiler-building.
2251 #
2252 # Thanks to Andreas Kunert for his wonderful LR(k) Pamphlet (German, see http://www.informatik.hu-berlin.de/~kunert/papers/lr-analyse), and Aho/Sethi/Ullman for their Dragon Book.
2253 #
2254 # Homepage:: http://shinobu.cYcnus.de (not existing yet)
2255 # Author:: murphy (Kornelius Kalnbach)
2256 # Copyright:: (cc) 2005 cYcnus
2257 # License:: GPL
2258 # Version:: 0.2.0 (2005-03-27)
2259
2260 require 'set_hash'
2261 require 'ctype'
2262 require 'tools'
2263 require 'rules'
2264 require 'trace'
2265
2266 require 'first'
2267 require 'follow'
2268
2269 # = Grammar
2270 #
2271 # == Syntax
2272 #
2273 # === Rules
2274 #
2275 # Each line is a rule.
2276 # The syntax is
2277 #
2278 # left - right
2279 #
2280 # where +left+ and +right+ can be uppercase and lowercase letters,
2281 # and <code>-</code> can be any combination of <, >, - or whitespace.
2282 #
2283 # === Symbols
2284 #
2285 # Uppercase letters stand for meta symbols, lowercase for terminals.
2286 #
2287 # You can make epsilon-derivations by leaving <code><right></code> empty.
2288 #
2289 # === Example
2290 # S - Ac
2291 # A - Sc
2292 # A - b
2293 # A -
2294 class Grammar
2295
2296 attr_reader :tracer
2297 # Creates a new Grammar.
2298 # If $trace is true, the algorithms explain (textual) what they do to $stdout.
2299 def initialize data, tracer = Tracer.new
2300 @tracer = tracer
2301 @rules = Rules.new
2302 @terminals, @meta_symbols = SortedSet.new, Array.new
2303 @start_symbol = nil
2304 add_rules data
2305 end
2306
2307 attr_reader :meta_symbols, :terminals, :rules, :start_symbol
2308
2309 alias_method :sigma, :terminals
2310 alias_method :alphabet, :terminals
2311 alias_method :variables, :meta_symbols
2312 alias_method :nonterminals, :meta_symbols
2313
2314 # A string representation of the grammar for debugging.
2315 def inspect productions_too = false
2316 'Grammar(meta symbols: %s; alphabet: %s; productions: [%s]; start symbol: %s)' %
2317 [
2318 meta_symbols.join(', '),
2319 terminals.join(', '),
2320 if productions_too
2321 @rules.inspect
2322 else
2323 @rules.size
2324 end,
2325 start_symbol
2326 ]
2327 end
2328
2329 # Add rules to the grammar. +rules+ should be a String or respond to +scan+ in a similar way.
2330 #
2331 # Syntax: see Grammar.
2332 def add_rules grammar
2333 @rules = Rules.parse grammar do |rule|
2334 @start_symbol ||= rule.left
2335 @meta_symbols << rule.left
2336 @terminals.merge rule.right.split('').select { |s| terminal? s }
2337 end
2338 @meta_symbols.uniq!
2339 update
2340 end
2341
2342 # Returns a hash acting as FIRST operator, so that
2343 # <code>first["ABC"]</code> is FIRST(ABC).
2344 # See http://en.wikipedia.org/wiki/LL_parser "Constructing an LL(1) parsing table" for details.
2345 def first
2346 first_operator
2347 end
2348
2349 # Returns a hash acting as FOLLOW operator, so that
2350 # <code>first["A"]</code> is FOLLOW(A).
2351 # See http://en.wikipedia.org/wiki/LL_parser "Constructing an LL(1) parsing table" for details.
2352 def follow
2353 follow_operator
2354 end
2355
2356 LLError = Class.new(Exception)
2357 LLErrorType1 = Class.new(LLError)
2358 LLErrorType2 = Class.new(LLError)
2359
2360 # Tests if the grammar is LL(1).
2361 def ll1?
2362 begin
2363 for meta in @meta_symbols
2364 first_sets = @rules[meta].map { |alpha| first[alpha] }
2365 first_sets.inject(Set[]) do |already_used, another_first_set|
2366 unless already_used.disjoint? another_first_set
2367 raise LLErrorType1
2368 end
2369 already_used.merge another_first_set
2370 end
2371
2372 if first[meta].include? EPSILON and not first[meta].disjoint? follow[meta]
2373 raise LLErrorType2
2374 end
2375 end
2376 rescue LLError
2377 false
2378 else
2379 true
2380 end
2381 end
2382
2383 private
2384
2385 def first_operator
2386 @first ||= FirstOperator.new self
2387 end
2388
2389 def follow_operator
2390 @follow ||= FollowOperator.new self
2391 end
2392
2393 def update
2394 @first = @follow = nil
2395 end
2396
2397 end
2398
2399 if $0 == __FILE__
2400 eval DATA.read, nil, $0, __LINE__+4
2401 end
2402
2403 require 'test/unit'
2404
2405 class TestCaseGrammar < Test::Unit::TestCase
2406
2407 include Grammar::Symbols
2408
2409 def fifo s
2410 Set[*s.split('')]
2411 end
2412
2413 def test_fifo
2414 assert_equal Set[], fifo('')
2415 assert_equal Set[EPSILON, END_OF_INPUT, 'x', 'Y'], fifo('?xY$')
2416 end
2417
2418 TEST_GRAMMAR_1 = <<-EOG
2419 S - ABCD
2420 A - a
2421 A -
2422 B - b
2423 B -
2424 C - c
2425 C -
2426 D - S
2427 D -
2428 EOG
2429
2430 def test_symbols
2431 assert EPSILON
2432 assert END_OF_INPUT
2433 end
2434
2435 def test_first_1
2436 g = Grammar.new TEST_GRAMMAR_1
2437
2438 f = nil
2439 assert_nothing_raised { f = g.first }
2440 assert_equal(Set['a', EPSILON], f['A'])
2441 assert_equal(Set['b', EPSILON], f['B'])
2442 assert_equal(Set['c', EPSILON], f['C'])
2443 assert_equal(Set['a', 'b', 'c', EPSILON], f['D'])
2444 assert_equal(f['D'], f['S'])
2445 end
2446
2447 def test_follow_1
2448 g = Grammar.new TEST_GRAMMAR_1
2449
2450 f = nil
2451 assert_nothing_raised { f = g.follow }
2452 assert_equal(Set['a', 'b', 'c', END_OF_INPUT], f['A'])
2453 assert_equal(Set['a', 'b', 'c', END_OF_INPUT], f['B'])
2454 assert_equal(Set['a', 'b', 'c', END_OF_INPUT], f['C'])
2455 assert_equal(Set[END_OF_INPUT], f['D'])
2456 assert_equal(Set[END_OF_INPUT], f['S'])
2457 end
2458
2459
2460 TEST_GRAMMAR_2 = <<-EOG
2461 S - Ed
2462 E - EpT
2463 E - EmT
2464 E - T
2465 T - TuF
2466 T - TdF
2467 T - F
2468 F - i
2469 F - n
2470 F - aEz
2471 EOG
2472
2473 def test_first_2
2474 g = Grammar.new TEST_GRAMMAR_2
2475
2476 f = nil
2477 assert_nothing_raised { f = g.first }
2478 assert_equal(Set['a', 'n', 'i'], f['E'])
2479 assert_equal(Set['a', 'n', 'i'], f['F'])
2480 assert_equal(Set['a', 'n', 'i'], f['T'])
2481 assert_equal(Set['a', 'n', 'i'], f['S'])
2482 end
2483
2484 def test_follow_2
2485 g = Grammar.new TEST_GRAMMAR_2
2486
2487 f = nil
2488 assert_nothing_raised { f = g.follow }
2489 assert_equal(Set['m', 'd', 'z', 'p'], f['E'])
2490 assert_equal(Set['m', 'd', 'z', 'p', 'u'], f['F'])
2491 assert_equal(Set['m', 'd', 'z', 'p', 'u'], f['T'])
2492 assert_equal(Set[END_OF_INPUT], f['S'])
2493 end
2494
2495 LLError = Grammar::LLError
2496
2497 TEST_GRAMMAR_3 = <<-EOG
2498 E - TD
2499 D - pTD
2500 D -
2501 T - FS
2502 S - uFS
2503 S -
2504 S - p
2505 F - aEz
2506 F - i
2507 EOG
2508
2509 NoError = Class.new(Exception)
2510
2511 def test_first_3
2512 g = Grammar.new TEST_GRAMMAR_3
2513
2514 # Grammar 3 is LL(1), so all first-sets must be disjoint.
2515 f = nil
2516 assert_nothing_raised { f = g.first }
2517 assert_equal(Set['a', 'i'], f['E'])
2518 assert_equal(Set[EPSILON, 'p'], f['D'])
2519 assert_equal(Set['a', 'i'], f['F'])
2520 assert_equal(Set['a', 'i'], f['T'])
2521 assert_equal(Set[EPSILON, 'u', 'p'], f['S'])
2522 for m in g.meta_symbols
2523 r = g.rules[m]
2524 firsts = r.map { |x| f[x] }.to_set
2525 assert_nothing_raised do
2526 firsts.inject(Set.new) do |already_used, another_first_set|
2527 raise LLError, 'not disjoint!' unless already_used.disjoint? another_first_set
2528 already_used.merge another_first_set
2529 end
2530 end
2531 end
2532 end
2533
2534 def test_follow_3
2535 g = Grammar.new TEST_GRAMMAR_3
2536
2537 # Grammar 3 is not LL(1), because epsilon is in FIRST(S),
2538 # but FIRST(S) and FOLLOW(S) are not disjoint.
2539 f = nil
2540 assert_nothing_raised { f = g.follow }
2541 assert_equal(Set['z', END_OF_INPUT], f['E'])
2542 assert_equal(Set['z', END_OF_INPUT], f['D'])
2543 assert_equal(Set['z', 'p', 'u', END_OF_INPUT], f['F'])
2544 assert_equal(Set['p', 'z', END_OF_INPUT], f['T'])
2545 assert_equal(Set['p', 'z', END_OF_INPUT], f['S'])
2546 for m in g.meta_symbols
2547 first_m = g.first[m]
2548 next unless first_m.include? EPSILON
2549 assert_raise(m == 'S' ? LLError : NoError) do
2550 if first_m.disjoint? f[m]
2551 raise NoError # this is fun :D
2552 else
2553 raise LLError
2554 end
2555 end
2556 end
2557 end
2558
2559 TEST_GRAMMAR_3b = <<-EOG
2560 E - TD
2561 D - pTD
2562 D - PTD
2563 D -
2564 T - FS
2565 S - uFS
2566 S -
2567 F - aEz
2568 F - i
2569 P - p
2570 EOG
2571
2572 def test_first_3b
2573 g = Grammar.new TEST_GRAMMAR_3b
2574
2575 # Grammar 3b is NOT LL(1), since not all first-sets are disjoint.
2576 f = nil
2577 assert_nothing_raised { f = g.first }
2578 assert_equal(Set['a', 'i'], f['E'])
2579 assert_equal(Set[EPSILON, 'p'], f['D'])
2580 assert_equal(Set['p'], f['P'])
2581 assert_equal(Set['a', 'i'], f['F'])
2582 assert_equal(Set['a', 'i'], f['T'])
2583 assert_equal(Set[EPSILON, 'u'], f['S'])
2584 for m in g.meta_symbols
2585 r = g.rules[m]
2586 firsts = r.map { |x| f[x] }
2587 assert_raise(m == 'D' ? LLError : NoError) do
2588 firsts.inject(Set.new) do |already_used, another_first_set|
2589 raise LLError, 'not disjoint!' unless already_used.disjoint? another_first_set
2590 already_used.merge another_first_set
2591 end
2592 raise NoError
2593 end
2594 end
2595 end
2596
2597 def test_follow_3b
2598 g = Grammar.new TEST_GRAMMAR_3b
2599
2600 # Although Grammar 3b is NOT LL(1), the FOLLOW-condition is satisfied.
2601 f = nil
2602 assert_nothing_raised { f = g.follow }
2603 assert_equal(fifo('z$'), f['E'], 'E')
2604 assert_equal(fifo('z$'), f['D'], 'D')
2605 assert_equal(fifo('ai'), f['P'], 'P')
2606 assert_equal(fifo('z$pu'), f['F'], 'F')
2607 assert_equal(fifo('z$p'), f['T'], 'T')
2608 assert_equal(fifo('z$p'), f['S'], 'S')
2609 for m in g.meta_symbols
2610 first_m = g.first[m]
2611 next unless first_m.include? EPSILON
2612 assert_raise(NoError) do
2613 if first_m.disjoint? f[m]
2614 raise NoError # this is fun :D
2615 else
2616 raise LLError
2617 end
2618 end
2619 end
2620 end
2621
2622 def test_ll1?
2623 assert_equal false, Grammar.new(TEST_GRAMMAR_3).ll1?, 'Grammar 3'
2624 assert_equal false, Grammar.new(TEST_GRAMMAR_3b).ll1?, 'Grammar 3b'
2625 end
2626
2627 def test_new
2628 assert_nothing_raised { Grammar.new '' }
2629 assert_nothing_raised { Grammar.new TEST_GRAMMAR_1 }
2630 assert_nothing_raised { Grammar.new TEST_GRAMMAR_2 }
2631 assert_nothing_raised { Grammar.new TEST_GRAMMAR_3 }
2632 assert_nothing_raised { Grammar.new TEST_GRAMMAR_1 + TEST_GRAMMAR_2 + TEST_GRAMMAR_3 }
2633 assert_raise(ArgumentError) { Grammar.new 'S - ?' }
2634 end
2635 end
2636
2637 # vim:foldmethod=syntax
2638
2639 #!/usr/bin/env ruby
2640
2641 require 'fox12'
2642
2643 include Fox
2644
2645 class Window < FXMainWindow
2646 def initialize(app)
2647 super(app, app.appName + ": First Set Calculation", nil, nil, DECOR_ALL, 0, 0, 800, 600, 0, 0)
2648
2649 # {{{ menubar
2650 menubar = FXMenuBar.new(self, LAYOUT_SIDE_TOP|LAYOUT_FILL_X)
2651
2652 filemenu = FXMenuPane.new(self)
2653
2654 FXMenuCommand.new(filemenu, "&Start\tCtl-S\tStart the application.", nil, getApp()).connect(SEL_COMMAND, method(:start))
2655 FXMenuCommand.new(filemenu, "&Quit\tAlt-F4\tQuit the application.", nil, getApp(), FXApp::ID_QUIT)
2656 FXMenuTitle.new(menubar, "&File", nil, filemenu)
2657 # }}} menubar
2658
2659 # {{{ statusbar
2660 @statusbar = FXStatusBar.new(self, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|STATUSBAR_WITH_DRAGCORNER)
2661 # }}} statusbar
2662
2663 # {{{ window content
2664 horizontalsplitt = FXSplitter.new(self, SPLITTER_VERTICAL|LAYOUT_SIDE_TOP|LAYOUT_FILL)
2665
2666
2667 @productions = FXList.new(horizontalsplitt, nil, 0, LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FIX_HEIGHT|LIST_SINGLESELECT)
2668 @productions.height = 100
2669
2670 @result = FXTable.new(horizontalsplitt, nil, 0, LAYOUT_FILL)
2671 @result.height = 200
2672 @result.setTableSize(2, 2, false)
2673 @result.rowHeaderWidth = 0
2674
2675 header = @result.columnHeader
2676 header.setItemText 0, 'X'
2677 header.setItemText 1, 'FIRST(X)'
2678 for item in header
2679 item.justification = FXHeaderItem::CENTER_X
2680 end
2681
2682 @debug = FXText.new(horizontalsplitt, nil, 0, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|LAYOUT_FIX_HEIGHT)
2683 @debug.height = 200
2684
2685 # }}} window content
2686 end
2687
2688 def load_grammar grammar
2689 @tracer = FirstTracer.new(self)
2690 @grammar = Grammar.new grammar, @tracer
2691 @rules_indexes = Hash.new
2692 @grammar.rules.each_with_index do |rule, i|
2693 @productions.appendItem rule.inspect
2694 @rules_indexes[rule] = i
2695 end
2696 end
2697
2698 def create
2699 super
2700 show(PLACEMENT_SCREEN)
2701 end
2702
2703 def rule rule
2704 @productions.selectItem @rules_indexes[rule]
2705 sleep 0.1
2706 end
2707
2708 def iterate i
2709 setTitle i.to_s
2710 sleep 0.1
2711 end
2712
2713 def missing what
2714 @debug.appendText what + "\n"
2715 sleep 0.1
2716 end
2717
2718 def start sender, sel, pointer
2719 Thread.new do
2720 begin
2721 @grammar.first
2722 rescue => boom
2723 @debug.appendText [boom.to_s, *boom.backtrace].join("\n")
2724 end
2725 end
2726 end
2727
2728 end
2729
2730 $: << 'grammar'
2731 require 'grammar'
2732
2733 require 'first_tracer'
2734
2735 app = FXApp.new("Shinobu", "cYcnus")
2736
2737 # fenster erzeugen
2738 window = Window.new app
2739
2740 unless ARGV.empty?
2741 grammar = File.read(ARGV.first)
2742 else
2743 grammar = <<-EOG1
2744 Z --> S
2745 S --> Sb
2746 S --> bAa
2747 A --> aSc
2748 A --> a
2749 A --> aSb
2750 EOG1
2751 end
2752
2753 window.load_grammar grammar
2754
2755 app.create
2756 app.run
2757
2758 require 'erb'
2759 require 'ftools'
2760 require 'yaml'
2761 require 'redcloth'
2762
2763 module WhyTheLuckyStiff
2764 class Book
2765 attr_accessor :author, :title, :terms, :image, :teaser,
2766 :chapters, :expansion_paks, :encoding, :credits
2767 def [] x
2768 @lang.fetch(x) do
2769 warn warning = "[not translated: '#{x}'!]"
2770 warning
2771 end
2772 end
2773 end
2774
2775 def Book::load( file_name )
2776 YAML::load( File.open( file_name ) )
2777 end
2778
2779 class Section
2780 attr_accessor :index, :header, :content
2781 def initialize( i, h, c )
2782 @index, @header, @content = i, h, RedCloth::new( c.to_s )
2783 end
2784 end
2785
2786 class Sidebar
2787 attr_accessor :title, :content
2788 end
2789
2790 YAML::add_domain_type( 'whytheluckystiff.net,2003', 'sidebar' ) do |taguri, val|
2791 YAML::object_maker( Sidebar, 'title' => val.keys.first, 'content' => RedCloth::new( val.values.first ) )
2792 end
2793 class Chapter
2794 attr_accessor :index, :title, :sections
2795 def initialize( i, t, sects )
2796 @index = i
2797 @title = t
2798 i = 0
2799 @sections = sects.collect do |s|
2800 if s.respond_to?( :keys )
2801 i += 1
2802 Section.new( i, s.keys.first, s.values.first )
2803 else
2804 s
2805 end
2806 end
2807 end
2808 end
2809
2810 YAML::add_domain_type( 'whytheluckystiff.net,2003', 'book' ) do |taguri, val|
2811 ['chapters', 'expansion_paks'].each do |chaptype|
2812 i = 0
2813 val[chaptype].collect! do |c|
2814 i += 1
2815 Chapter::new( i, c.keys.first, c.values.first )
2816 end
2817 end
2818 val['teaser'].collect! do |t|
2819 Section::new( 1, t.keys.first, t.values.first )
2820 end
2821 val['terms'] = RedCloth::new( val['terms'] )
2822 YAML::object_maker( Book, val )
2823 end
2824
2825 class Image
2826 attr_accessor :file_name
2827 end
2828
2829 YAML::add_domain_type( 'whytheluckystiff.net,2003', 'img' ) do |taguri, val|
2830 YAML::object_maker( Image, 'file_name' => "i/" + val )
2831 end
2832 end
2833
2834 #
2835 # Convert the book to HTML
2836 #
2837 if __FILE__ == $0
2838 unless ARGV[0]
2839 puts "Usage: #{$0} [/path/to/save/html]"
2840 exit
2841 end
2842
2843 site_path = ARGV[0]
2844 book = WhyTheLuckyStiff::Book::load( 'poignant.yml' )
2845 chapter = nil
2846
2847 # Write index page
2848 index_tpl = ERB::new( File.open( 'index.erb' ).read )
2849 File.open( File.join( site_path, 'index.html' ), 'w' ) do |out|
2850 out << index_tpl.result
2851 end
2852
2853 book.chapters = book.chapters[0,3] if ARGV.include? '-fast'
2854
2855 # Write chapter pages
2856 chapter_tpl = ERB::new( File.open( 'chapter.erb' ).read )
2857 book.chapters.each do |chapter|
2858 File.open( File.join( site_path, "chapter-#{ chapter.index }.html" ), 'w' ) do |out|
2859 out << chapter_tpl.result
2860 end
2861 end
2862 exit if ARGV.include? '-fast'
2863
2864 # Write expansion pak pages
2865 expak_tpl = ERB::new( File.open( 'expansion-pak.erb' ).read )
2866 book.expansion_paks.each do |pak|
2867 File.open( File.join( site_path, "expansion-pak-#{ pak.index }.html" ), 'w' ) do |out|
2868 out << expak_tpl.result( binding )
2869 end
2870 end
2871
2872 # Write printable version
2873 print_tpl = ERB::new( File.open( 'print.erb' ).read )
2874 File.open( File.join( site_path, "print.html" ), 'w' ) do |out|
2875 out << print_tpl.result
2876 end
2877
2878 # Copy css + images into site
2879 copy_list = ["guide.css"] +
2880 Dir["i/*"].find_all { |image| image =~ /\.(gif|jpg|png)$/ }
2881
2882 File.makedirs( File.join( site_path, "i" ) )
2883 copy_list.each do |copy_file|
2884 File.copy( copy_file, File.join( site_path, copy_file ) )
2885 end
2886 end
2887
2888 #!/usr/bin/env ruby
2889
2890 require 'fox'
2891 begin
2892 require 'opengl'
2893 rescue LoadError
2894 require 'fox/missingdep'
2895 MSG = <<EOM
2896 Sorry, this example depends on the OpenGL extension. Please
2897 check the Ruby Application Archives for an appropriate
2898 download site.
2899 EOM
2900 missingDependency(MSG)
2901 end
2902
2903
2904 include Fox
2905 include Math
2906
2907 Deg2Rad = Math::PI / 180
2908
2909 D_MAX = 6
2910 SQUARE_SIZE = 2.0 / D_MAX
2911 SQUARE_DISTANCE = 4.0 / D_MAX
2912 AMPLITUDE = SQUARE_SIZE
2913 LAMBDA = D_MAX.to_f / 2
2914
2915 class GLTestWindow < FXMainWindow
2916
2917 # How often our timer will fire (in milliseconds)
2918 TIMER_INTERVAL = 500
2919
2920 # Rotate the boxes when a timer message is received
2921 def onTimeout(sender, sel, ptr)
2922 @angle += 10.0
2923 # @size = 0.5 + 0.2 * Math.cos(Deg2Rad * @angle)
2924 drawScene()
2925 @timer = getApp().addTimeout(TIMER_INTERVAL, method(:onTimeout))
2926 end
2927
2928 # Rotate the boxes when a chore message is received
2929 def onChore(sender, sel, ptr)
2930 @angle += 10.0
2931 # @angle %= 360.0
2932 # @size = 0.5 + 0.2 * Math.cos(Deg2Rad * @angle)
2933 drawScene()
2934 @chore = getApp().addChore(method(:onChore))
2935 end
2936
2937 # Draw the GL scene
2938 def drawScene
2939 lightPosition = [15.0, 10.0, 5.0, 1.0]
2940 lightAmbient = [ 0.1, 0.1, 0.1, 1.0]
2941 lightDiffuse = [ 0.9, 0.9, 0.9, 1.0]
2942 redMaterial = [ 0.0, 0.0, 1.0, 1.0]
2943 blueMaterial = [ 0.0, 1.0, 0.0, 1.0]
2944
2945 width = @glcanvas.width.to_f
2946 height = @glcanvas.height.to_f
2947 aspect = width/height
2948
2949 # Make context current
2950 @glcanvas.makeCurrent()
2951
2952 GL.Viewport(0, 0, @glcanvas.width, @glcanvas.height)
2953
2954 GL.ClearColor(1.0/256, 0.0, 5.0/256, 1.0)
2955 GL.Clear(GL::COLOR_BUFFER_BIT|GL::DEPTH_BUFFER_BIT)
2956 GL.Enable(GL::DEPTH_TEST)
2957
2958 GL.Disable(GL::DITHER)
2959
2960 GL.MatrixMode(GL::PROJECTION)
2961 GL.LoadIdentity()
2962 GLU.Perspective(30.0, aspect, 1.0, 100.0)
2963
2964 GL.MatrixMode(GL::MODELVIEW)
2965 GL.LoadIdentity()
2966 GLU.LookAt(5.0, 10.0, 15.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
2967
2968 GL.ShadeModel(GL::SMOOTH)
2969 GL.Light(GL::LIGHT0, GL::POSITION, lightPosition)
2970 GL.Light(GL::LIGHT0, GL::AMBIENT, lightAmbient)
2971 GL.Light(GL::LIGHT0, GL::DIFFUSE, lightDiffuse)
2972 GL.Enable(GL::LIGHT0)
2973 GL.Enable(GL::LIGHTING)
2974
2975 GL.Rotated(0.1*@angle, 0.0, 1.0, 0.0)
2976 for x in -D_MAX..D_MAX
2977 for y in -D_MAX..D_MAX
2978 h1 = (x + y - 2).abs
2979 h2 = (y - x + 1).abs
2980 GL.PushMatrix
2981 c = [1, 0, 0, 1]
2982 GL.Material(GL::FRONT, GL::AMBIENT, c)
2983 GL.Material(GL::FRONT, GL::DIFFUSE, c)
2984
2985 GL.Translated(
2986 y * SQUARE_DISTANCE,
2987 AMPLITUDE * h1,
2988 x * SQUARE_DISTANCE
2989 )
2990
2991 GL.Begin(GL::TRIANGLE_STRIP)
2992 GL.Normal(1.0, 0.0, 0.0)
2993 GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
2994 GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
2995 GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
2996 GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
2997 GL.End
2998
2999 GL.PopMatrix
3000
3001 GL.PushMatrix
3002 c = [0, 0, 1, 1]
3003 GL.Material(GL::FRONT, GL::AMBIENT, c)
3004 GL.Material(GL::FRONT, GL::DIFFUSE, c)
3005
3006 GL.Translated(
3007 y * SQUARE_DISTANCE,
3008 AMPLITUDE * h2,
3009 x * SQUARE_DISTANCE
3010 )
3011
3012 GL.Begin(GL::TRIANGLE_STRIP)
3013 GL.Normal(1.0, 0.0, 0.0)
3014 GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
3015 GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
3016 GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
3017 GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
3018 GL.End
3019
3020 GL.PopMatrix
3021
3022 GL.PushMatrix
3023 c = [0.0 + (x/10.0), 0.0 + (y/10.0), 0, 1]
3024 GL.Material(GL::FRONT, GL::AMBIENT, c)
3025 GL.Material(GL::FRONT, GL::DIFFUSE, c)
3026
3027 GL.Translated(
3028 y * SQUARE_DISTANCE,
3029 0,
3030 x * SQUARE_DISTANCE
3031 )
3032
3033 GL.Begin(GL::TRIANGLE_STRIP)
3034 GL.Normal(1.0, 0.0, 0.0)
3035 GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
3036 GL.Vertex(-SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
3037 GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, -SQUARE_SIZE)
3038 GL.Vertex(+SQUARE_SIZE, +SQUARE_SIZE, +SQUARE_SIZE)
3039 GL.End
3040
3041 GL.PopMatrix
3042 end
3043 end
3044
3045 # Swap if it is double-buffered
3046 if @glvisual.isDoubleBuffer
3047 @glcanvas.swapBuffers
3048 end
3049
3050 # Make context non-current
3051 @glcanvas.makeNonCurrent
3052 end
3053
3054 def initialize(app)
3055 # Invoke the base class initializer
3056 super(app, "OpenGL Test Application", nil, nil, DECOR_ALL, 0, 0, 1024, 768)
3057
3058 # Construct the main window elements
3059 frame = FXHorizontalFrame.new(self, LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y)
3060 frame.padLeft, frame.padRight = 0, 0
3061 frame.padTop, frame.padBottom = 0, 0
3062
3063 # Left pane to contain the glcanvas
3064 glcanvasFrame = FXVerticalFrame.new(frame,
3065 LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT)
3066 glcanvasFrame.padLeft, glcanvasFrame.padRight = 10, 10
3067 glcanvasFrame.padTop, glcanvasFrame.padBottom = 10, 10
3068
3069 # Label above the glcanvas
3070 FXLabel.new(glcanvasFrame, "OpenGL Canvas Frame", nil,
3071 JUSTIFY_CENTER_X|LAYOUT_FILL_X)
3072
3073 # Horizontal divider line
3074 FXHorizontalSeparator.new(glcanvasFrame, SEPARATOR_GROOVE|LAYOUT_FILL_X)
3075
3076 # Drawing glcanvas
3077 glpanel = FXVerticalFrame.new(glcanvasFrame, (FRAME_SUNKEN|FRAME_THICK|
3078 LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT))
3079 glpanel.padLeft, glpanel.padRight = 0, 0
3080 glpanel.padTop, glpanel.padBottom = 0, 0
3081
3082 # A visual to draw OpenGL
3083 @glvisual = FXGLVisual.new(getApp(), VISUAL_DOUBLEBUFFER)
3084
3085 # Drawing glcanvas
3086 @glcanvas = FXGLCanvas.new(glpanel, @glvisual, nil, 0,
3087 LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT)
3088 @glcanvas.connect(SEL_PAINT) {
3089 drawScene
3090 }
3091 @glcanvas.connect(SEL_CONFIGURE) {
3092 if @glcanvas.makeCurrent
3093 GL.Viewport(0, 0, @glcanvas.width, @glcanvas.height)
3094 @glcanvas.makeNonCurrent
3095 end
3096 }
3097
3098 # Right pane for the buttons
3099 buttonFrame = FXVerticalFrame.new(frame, LAYOUT_FILL_Y|LAYOUT_TOP|LAYOUT_LEFT)
3100 buttonFrame.padLeft, buttonFrame.padRight = 10, 10
3101 buttonFrame.padTop, buttonFrame.padBottom = 10, 10
3102
3103 # Label above the buttons
3104 FXLabel.new(buttonFrame, "Button Frame", nil,
3105 JUSTIFY_CENTER_X|LAYOUT_FILL_X)
3106
3107 # Horizontal divider line
3108 FXHorizontalSeparator.new(buttonFrame, SEPARATOR_RIDGE|LAYOUT_FILL_X)
3109
3110 # Spin according to timer
3111 spinTimerBtn = FXButton.new(buttonFrame,
3112 "Spin &Timer\tSpin using interval timers\nNote the app
3113 blocks until the interal has elapsed...", nil,
3114 nil, 0, FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
3115 spinTimerBtn.padLeft, spinTimerBtn.padRight = 10, 10
3116 spinTimerBtn.padTop, spinTimerBtn.padBottom = 5, 5
3117 spinTimerBtn.connect(SEL_COMMAND) {
3118 @spinning = true
3119 @timer = getApp().addTimeout(TIMER_INTERVAL, method(:onTimeout))
3120 }
3121 spinTimerBtn.connect(SEL_UPDATE) { |sender, sel, ptr|
3122 @spinning ? sender.disable : sender.enable
3123 }
3124
3125 # Spin according to chore
3126 spinChoreBtn = FXButton.new(buttonFrame,
3127 "Spin &Chore\tSpin as fast as possible using chores\nNote even though the
3128 app is very responsive, it never blocks;\nthere is always something to
3129 do...", nil,
3130 nil, 0, FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
3131 spinChoreBtn.padLeft, spinChoreBtn.padRight = 10, 10
3132 spinChoreBtn.padTop, spinChoreBtn.padBottom = 5, 5
3133 spinChoreBtn.connect(SEL_COMMAND) {
3134 @spinning = true
3135 @chore = getApp().addChore(method(:onChore))
3136 }
3137 spinChoreBtn.connect(SEL_UPDATE) { |sender, sel, ptr|
3138 @spinning ? sender.disable : sender.enable
3139 }
3140
3141 # Stop spinning
3142 stopBtn = FXButton.new(buttonFrame,
3143 "&Stop Spin\tStop this mad spinning, I'm getting dizzy", nil,
3144 nil, 0, FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
3145 stopBtn.padLeft, stopBtn.padRight = 10, 10
3146 stopBtn.padTop, stopBtn.padBottom = 5, 5
3147 stopBtn.connect(SEL_COMMAND) {
3148 @spinning = false
3149 if @timer
3150 getApp().removeTimeout(@timer)
3151 @timer = nil
3152 end
3153 if @chore
3154 getApp().removeChore(@chore)
3155 @chore = nil
3156 end
3157 }
3158 stopBtn.connect(SEL_UPDATE) { |sender, sel, ptr|
3159 @spinning ? sender.enable : sender.disable
3160 }
3161
3162 # Exit button
3163 exitBtn = FXButton.new(buttonFrame, "&Exit\tExit the application", nil,
3164 getApp(), FXApp::ID_QUIT,
3165 FRAME_THICK|FRAME_RAISED|LAYOUT_FILL_X|LAYOUT_TOP|LAYOUT_LEFT)
3166 exitBtn.padLeft, exitBtn.padRight = 10, 10
3167 exitBtn.padTop, exitBtn.padBottom = 5, 5
3168
3169 # Make a tooltip
3170 FXTooltip.new(getApp())
3171
3172 # Initialize private variables
3173 @spinning = false
3174 @chore = nil
3175 @timer = nil
3176 @angle = 0.0
3177 @size = 0.5
3178 end
3179
3180 # Create and initialize
3181 def create
3182 super
3183 show(PLACEMENT_SCREEN)
3184 end
3185 end
3186
3187 if __FILE__ == $0
3188 # Construct the application
3189 application = FXApp.new("GLTest", "FoxTest")
3190
3191 # To ensure that the chores-based spin will run as fast as possible,
3192 # we can disable the chore in FXRuby's event loop that tries to schedule
3193 # other threads. This is OK for this program because there aren't any
3194 # other Ruby threads running.
3195
3196 #application.disableThreads
3197
3198 # Construct the main window
3199 GLTestWindow.new(application)
3200
3201 # Create the app's windows
3202 application.create
3203
3204 # Run the application
3205 application.run
3206 end
3207
3208 class Facelet
3209 attr_accessor :color
3210 def initialize(color)
3211 @color = color
3212 end
3213
3214 def to_s
3215 @color
3216 end
3217 end
3218
3219 class Edge
3220 attr_accessor :facelets, :colors
3221
3222 def initialize(facelets)
3223 @facelets = facelets
3224 @colors = @facelets.map { |fl| fl.color }
3225 end
3226
3227 def apply(edge)
3228 @facelets.each_with_index { |fl, i|
3229 fl.color = edge.colors[i]
3230 }
3231 end
3232
3233 def inspect
3234 "\n%s %s\n%s %s %s" % facelets
3235 end
3236 end
3237
3238 class Side
3239 attr_reader :num, :facelets
3240 attr_accessor :sides
3241
3242 def initialize(num)
3243 @num = num
3244 @sides = []
3245 @facelets = []
3246 @fl_by_side = {}
3247 end
3248
3249 # facelets & sides
3250 # 0
3251 # 0 1 2
3252 # 3 3 4 5 1
3253 # 6 7 8
3254 # 2
3255
3256 def facelets=(facelets)
3257 @facelets = facelets.map { |c| Facelet.new(c) }
3258 init_facelet 0, 3,0
3259 init_facelet 1, 0
3260 init_facelet 2, 0,1
3261 init_facelet 3, 3
3262 init_facelet 5, 1
3263 init_facelet 6, 2,3
3264 init_facelet 7, 2
3265 init_facelet 8, 1,2
3266 end
3267
3268 def <=>(side)
3269 self.num <=> side.num
3270 end
3271
3272 def init_facelet(pos, *side_nums)
3273 sides = side_nums.map { |num| @sides[num] }.sort
3274 @fl_by_side[sides] = pos
3275 end
3276
3277 def []=(color, *sides)
3278 @facelets[@fl_by_side[sides.sort]].color = color
3279 end
3280
3281 def values_at(*sides)
3282 sides.map { |sides| @facelets[@fl_by_side[sides.sort]] }
3283 end
3284
3285 def inspect(range=nil)
3286 if range
3287 @facelets.values_at(*(range.to_a)).join(' ')
3288 else
3289 <<-EOS.gsub(/\d/) { |num| @facelets[num.to_i] }.gsub(/[ABCD]/) { |side| @sides[side[0]-?A].num.to_s }
3290 A
3291 0 1 2
3292 D 3 4 5 B
3293 6 7 8
3294 C
3295 EOS
3296 end
3297 end
3298
3299 def get_edge(side)
3300 trio = (-1..1).map { |x| (side + x) % 4 }
3301 prev_side, this_side, next_side = @sides.values_at(*trio)
3302 e = Edge.new(
3303 self .values_at( [this_side], [this_side, next_side] ) +
3304 this_side.values_at( [self, prev_side], [self ], [self, next_side] )
3305 )
3306 #puts 'Edge created for side %d: ' % side + e.inspect
3307 e
3308 end
3309
3310 def turn(dir)
3311 #p 'turn side %d in %d' % [num, dir]
3312 edges = (0..3).map { |n| get_edge n }
3313 for i in 0..3
3314 edges[i].apply edges[(i-dir) % 4]
3315 end
3316 end
3317 end
3318
3319 class Cube
3320 def initialize
3321 @sides = []
3322 %w(left front right back top bottom).each_with_index { |side, i|
3323 eval("@sides[#{i}] = @#{side} = Side.new(#{i})")
3324 }
3325 @left.sides = [@top, @front, @bottom, @back]
3326 @front.sides = [@top, @right, @bottom, @left]
3327 @right.sides = [@top, @back, @bottom, @front]
3328 @back.sides = [@top, @left, @bottom, @right]
3329 @top.sides = [@back, @right, @front, @left]
3330 @bottom.sides = [@front, @right, @back, @left]
3331 end
3332
3333 def read_facelets(fs)
3334 pattern = Regexp.new(<<-EOP.gsub(/\w/, '\w').gsub(/\s+/, '\s*'))
3335 (w w w)
3336 (w w w)
3337 (w w w)
3338 (r r r) (g g g) (b b b) (o o o)
3339 (r r r) (g g g) (b b b) (o o o)
3340 (r r r) (g g g) (b b b) (o o o)
3341 (y y y)
3342 (y y y)
3343 (y y y)
3344 EOP
3345 md = pattern.match(fs).to_a
3346
3347 @top.facelets = parse_facelets(md.values_at(1,2,3))
3348 @left.facelets = parse_facelets(md.values_at(4,8,12))
3349 @front.facelets = parse_facelets(md.values_at(5,9,13))
3350 @right.facelets = parse_facelets(md.values_at(6,10,14))
3351 @back.facelets = parse_facelets(md.values_at(7,11,15))
3352 @bottom.facelets = parse_facelets(md.values_at(16,17,18))
3353 end
3354
3355 def turn(side, dir)
3356 #p 'turn %d in %d' % [side, dir]
3357 @sides[side].turn(dir)
3358 #puts inspect
3359 end
3360
3361 def inspect
3362 <<-EOF.gsub(/(\d):(\d)-(\d)/) { @sides[$1.to_i].inspect(Range.new($2.to_i, $3.to_i)) }
3363 4:0-2
3364 4:3-5
3365 4:6-8
3366 0:0-2 1:0-2 2:0-2 3:0-2
3367 0:3-5 1:3-5 2:3-5 3:3-5
3368 0:6-8 1:6-8 2:6-8 3:6-8
3369 5:0-2
3370 5:3-5
3371 5:6-8
3372 EOF
3373 end
3374
3375 private
3376 def parse_facelets(rows)
3377 rows.join.delete(' ').split(//)
3378 end
3379 end
3380
3381 #$stdin = DATA
3382
3383 gets.to_i.times do |i|
3384 puts "Scenario ##{i+1}:"
3385 fs = ''
3386 9.times { fs << gets }
3387 cube = Cube.new
3388 cube.read_facelets fs
3389 gets.to_i.times do |t|
3390 side, dir = gets.split.map {|s| s.to_i}
3391 cube.turn(side, dir)
3392 end
3393 puts cube.inspect
3394 puts
3395 end
3396
3397 # 2004 by murphy <[email protected]>
3398 # GPL
3399 class Scenario
3400 class TimePoint
3401 attr_reader :data
3402 def initialize *data
3403 @data = data
3404 end
3405
3406 def [] i
3407 @data[i] or 0
3408 end
3409
3410 include Comparable
3411 def <=> tp
3412 r = 0
3413 [@data.size, tp.data.size].max.times do |i|
3414 r = self[i] <=> tp[i]
3415 return r if r.nonzero?
3416 end
3417 0
3418 end
3419
3420 def - tp
3421 r = []
3422 [@data.size, tp.data.size].max.times do |i|
3423 r << self[i] - tp[i]
3424 end
3425 r
3426 end
3427
3428 def inspect
3429 # 01/01/1800 00:00:00
3430 '%02d/%02d/%04d %02d:%02d:%02d' % @data.values_at(1, 2, 0, 3, 4, 5)
3431 end
3432 end
3433
3434 ONE_HOUR = TimePoint.new 0, 0, 0, 1, 0, 0
3435
3436 APPOINTMENT_PATTERN = /
3437 ( \d{4} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s
3438 ( \d{4} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} ) \s ( \d{2} )
3439 /x
3440
3441 def initialize io
3442 @team_size = io.gets.to_i
3443 @data = [ [TimePoint.new(1800, 01, 01, 00, 00, 00), @team_size] ]
3444 @team_size.times do # each team member
3445 io.gets.to_i.times do # each appointment
3446 m = APPOINTMENT_PATTERN.match io.gets
3447 @data << [TimePoint.new(*m.captures[0,6].map { |x| x.to_i }), -1]
3448 @data << [TimePoint.new(*m.captures[6,6].map { |x| x.to_i }), +1]
3449 end
3450 end
3451 @data << [TimePoint.new(2200, 01, 01, 00, 00, 00), -@team_size]
3452 end
3453
3454 def print_time_plan
3455 n = 0
3456 appointment = nil
3457 no_appointment = true
3458 @data.sort_by { |x| x[0] }.each do |x|
3459 tp, action = *x
3460 n += action
3461 # at any time during the meeting, at least two team members need to be there
3462 # and at most one team member is allowed to be absent
3463 if n >= 2 and (@team_size - n) <= 1
3464 appointment ||= tp
3465 else
3466 if appointment
3467 # the meeting should be at least one hour in length
3468 if TimePoint.new(*(tp - appointment)) >= ONE_HOUR
3469 puts 'appointment possible from %p to %p' % [appointment, tp]
3470 no_appointment = false
3471 end
3472 appointment = false
3473 end
3474 end
3475 end
3476 puts 'no appointment possible' if no_appointment
3477 end
3478 end
3479
3480 # read the data
3481 DATA.gets.to_i.times do |si| # each scenario
3482 puts 'Scenario #%d:' % (si + 1)
3483 sc = Scenario.new DATA
3484 sc.print_time_plan
3485 puts
3486 end
3487
3488 #__END__
3489 2
3490 3
3491 3
3492 2002 06 28 15 00 00 2002 06 28 18 00 00 TUD Contest Practice Session
3493 2002 06 29 10 00 00 2002 06 29 15 00 00 TUD Contest
3494 2002 11 15 15 00 00 2002 11 17 23 00 00 NWERC Delft
3495 4
3496 2002 06 25 13 30 00 2002 06 25 15 30 00 FIFA World Cup Semifinal I
3497 2002 06 26 13 30 00 2002 06 26 15 30 00 FIFA World Cup Semifinal II
3498 2002 06 29 13 00 00 2002 06 29 15 00 00 FIFA World Cup Third Place
3499 2002 06 30 13 00 00 2002 06 30 15 00 00 FIFA World Cup Final
3500 1
3501 2002 06 01 00 00 00 2002 06 29 18 00 00 Preparation of Problem Set
3502 2
3503 1
3504 1800 01 01 00 00 00 2200 01 01 00 00 00 Solving Problem 8
3505 0
3506
3507 require 'token_consts'
3508 require 'symbol'
3509 require 'ctype'
3510 require 'error'
3511
3512 class Fixnum
3513 # Treat char as a digit and return it's value as Fixnum.
3514 # Returns nonsense for non-digits.
3515 # Examples:
3516 # <code>
3517 # RUBY_VERSION[0].digit == '1.8.2'[0].digit == 1
3518 # </code>
3519 #
3520 # <code>
3521 # ?6.digit == 6
3522 # </code>
3523 #
3524 # <code>
3525 # ?A.digit == 17
3526 # </code>
3527 def digit
3528 self - ?0
3529 end
3530 end
3531
3532 ##
3533 # Stellt einen einfachen Scanner für die lexikalische Analyse der Sprache Pas-0 dar.
3534 #
3535 # @author Andreas Kunert
3536 # Ruby port by murphy
3537 class Scanner
3538
3539 include TokenConsts
3540
3541 attr_reader :line, :pos
3542
3543 # To allow Scanner.new without parameters.
3544 DUMMY_INPUT = 'dummy file'
3545 def DUMMY_INPUT.getc
3546 nil
3547 end
3548
3549 ##
3550 # Erzeugt einen Scanner, der als Eingabe das übergebene IO benutzt.
3551 def initialize input = DUMMY_INPUT
3552 @line = 1
3553 @pos = 0
3554
3555 begin
3556 @input = input
3557 @next_char = @input.getc
3558 rescue IOError # TODO show the reason!
3559 Error.ioError
3560 raise
3561 end
3562 end
3563
3564 ##
3565 # Liest das nchste Zeichen von der Eingabe.
3566 def read_next_char
3567 begin
3568 @pos += 1
3569 @current_char = @next_char
3570 @next_char = @input.getc
3571 rescue IOError
3572 Error.ioError
3573 raise
3574 end
3575 end
3576
3577 ##
3578 # Sucht das nächste Symbol, identifiziert es, instantiiert ein entsprechendes
3579 # PascalSymbol-Objekt und gibt es zurück.
3580 # @see Symbol
3581 # @return das gefundene Symbol als PascalSymbol-Objekt
3582 def get_symbol
3583 current_symbol = nil
3584 until current_symbol
3585 read_next_char
3586
3587 if @current_char.alpha?
3588 identifier = @current_char.chr
3589 while @next_char.alpha? or @next_char.digit?
3590 identifier << @next_char
3591 read_next_char
3592 end
3593 current_symbol = handle_identifier(identifier.upcase)
3594 elsif @current_char.digit?
3595 current_symbol = number
3596 else
3597 case @current_char
3598 when ?\s
3599 # ignore
3600 when ?\n
3601 new_line
3602 when nil
3603 current_symbol = PascalSymbol.new EOP
3604 when ?{
3605 comment
3606
3607 when ?:
3608 if @next_char == ?=
3609 read_next_char
3610 current_symbol = PascalSymbol.new BECOMES
3611 else
3612 current_symbol = PascalSymbol.new COLON
3613 end
3614
3615 when ?<
3616 if (@next_char == ?=)
3617 read_next_char
3618 current_symbol = PascalSymbol.new LEQSY
3619 elsif (@next_char == ?>)
3620 read_next_char
3621 current_symbol = PascalSymbol.new NEQSY
3622 else
3623 current_symbol = PascalSymbol.new LSSSY
3624 end
3625
3626 when ?>
3627 if (@next_char == ?=)
3628 read_next_char
3629 current_symbol = PascalSymbol.new GEQSY
3630 else
3631 current_symbol = PascalSymbol.new GRTSY
3632 end
3633
3634 when ?. then current_symbol = PascalSymbol.new PERIOD
3635 when ?( then current_symbol = PascalSymbol.new LPARENT
3636 when ?, then current_symbol = PascalSymbol.new COMMA
3637 when ?* then current_symbol = PascalSymbol.new TIMES
3638 when ?/ then current_symbol = PascalSymbol.new SLASH
3639 when ?+ then current_symbol = PascalSymbol.new PLUS
3640 when ?- then current_symbol = PascalSymbol.new MINUS
3641 when ?= then current_symbol = PascalSymbol.new EQLSY
3642 when ?) then current_symbol = PascalSymbol.new RPARENT
3643 when ?; then current_symbol = PascalSymbol.new SEMICOLON
3644 else
3645 Error.error(100, @line, @pos) if @current_char > ?\s
3646 end
3647 end
3648 end
3649 current_symbol
3650 end
3651
3652 private
3653 ##
3654 # Versucht, in dem gegebenen String ein Schlüsselwort zu erkennen.
3655 # Sollte dabei ein Keyword gefunden werden, so gibt er ein PascalSymbol-Objekt zurück, das
3656 # das entsprechende Keyword repräsentiert. Ansonsten besteht die Rückgabe aus
3657 # einem SymbolIdent-Objekt (abgeleitet von PascalSymbol), das den String 1:1 enthält
3658 # @see symbol
3659 # @return falls Keyword gefunden, zugehöriges PascalSymbol, sonst SymbolIdent
3660 def handle_identifier identifier
3661 if sym = KEYWORD_SYMBOLS[identifier]
3662 PascalSymbol.new sym
3663 else
3664 SymbolIdent.new identifier
3665 end
3666 end
3667
3668 MAXINT = 2**31 - 1
3669 MAXINT_DIV_10 = MAXINT / 10
3670 MAXINT_MOD_10 = MAXINT % 10
3671 ##
3672 # Versucht, aus dem gegebenen Zeichen und den folgenden eine Zahl zusammenzusetzen.
3673 # Dabei wird der relativ intuitive Algorithmus benutzt, die endgültige Zahl bei
3674 # jeder weiteren Ziffer mit 10 zu multiplizieren und diese dann mit der Ziffer zu
3675 # addieren. Sonderfälle bestehen dann nur noch in der Behandlung von reellen Zahlen.
3676 # <BR>
3677 # Treten dabei kein Punkt oder ein E auf, so gibt diese Methode ein SymbolIntCon-Objekt
3678 # zurück, ansonsten (reelle Zahl) ein SymbolRealCon-Objekt. Beide Symbole enthalten
3679 # jeweils die Zahlwerte.
3680 # <BR>
3681 # Anmerkung: Diese Funktion ist mit Hilfe der Java/Ruby-API deutlich leichter zu realisieren.
3682 # Sie wurde dennoch so implementiert, um den Algorithmus zu demonstrieren
3683 # @see symbol
3684 # @return SymbolIntcon- oder SymbolRealcon-Objekt, das den Zahlwert enthält
3685 def number
3686 is_integer = true
3687 integer_too_long = false
3688 exponent = 0
3689 exp_counter = -1
3690 exp_sign = 1
3691
3692 integer_mantisse = @current_char.digit
3693
3694 while (@next_char.digit? and integer_mantisse < MAXINT_DIV_10) or
3695 (integer_mantisse == MAXINT_DIV_10 and @next_char.digit <= MAXINT_MOD_10)
3696 integer_mantisse *= 10
3697 integer_mantisse += @next_char.digit
3698 read_next_char
3699 end
3700
3701 real_mantisse = integer_mantisse
3702
3703 while @next_char.digit?
3704 integer_too_long = true
3705 real_mantisse *= 10
3706 real_mantisse += @next_char.digit
3707 read_next_char
3708 end
3709 if @next_char == ?.
3710 read_next_char
3711 is_integer = false
3712 unless @next_char.digit?
3713 Error.error 101, @line, @pos
3714 end
3715 while @next_char.digit?
3716 real_mantisse += @next_char.digit * (10 ** exp_counter)
3717 read_next_char
3718 exp_counter -= 1
3719 end
3720 end
3721 if @next_char == ?E
3722 is_integer = false
3723 read_next_char
3724 if @next_char == ?-
3725 exp_sign = -1
3726 read_next_char
3727 end
3728 unless @next_char.digit?
3729 Error.error 101, @line, @pos
3730 end
3731 while @next_char.digit?
3732 exponent *= 10
3733 exponent += @next_char.digit
3734 read_next_char
3735 end
3736 end
3737
3738 if is_integer
3739 if integer_too_long
3740 Error.error 102, @line, @pos
3741 end
3742 SymbolIntcon.new integer_mantisse
3743 else
3744 SymbolRealcon.new real_mantisse * (10 ** (exp_sign * exponent))
3745 end
3746 end
3747
3748 ##
3749 # Sorgt für ein Überlesen von Kommentaren.
3750 # Es werden einfach alle Zeichen bis zu einer schließenden Klammer eingelesen
3751 # und verworfen.
3752 def comment
3753 while @current_char != ?}
3754 forbid_eop
3755 new_line if @current_char == ?\n
3756 read_next_char
3757 end
3758 end
3759
3760 def new_line
3761 @line += 1
3762 @pos = 0
3763 end
3764
3765 def forbid_eop
3766 if eop?
3767 Error.error 103, @line, @pos
3768 end
3769 exit
3770 end
3771
3772 def eop?
3773 @current_char.nil?
3774 end
3775 end
3776
3777 ##
3778 # Läßt ein Testprogramm ablaufen.
3779 # Dieses erzeugt sich ein Scanner-Objekt und ruft an diesem kontinuierlich bis zum Dateiende
3780 # get_symbol auf.
3781 if $0 == __FILE__
3782 scan = Scanner.new(File.new(ARGV[0] || 'test.pas'))
3783 loop do
3784 c = scan.get_symbol
3785 puts c
3786 break if c.typ == TokenConsts::EOP
3787 end
3788 end
3789 # -*- ruby -*-
3790
3791 # Local variables:
3792 # indent-tabs-mode: nil
3793 # ruby-indent-level: 4
3794 # End:
3795
3796 # @@PLEAC@@_NAME
3797 # @@SKIP@@ Ruby
3798
3799 # @@PLEAC@@_WEB
3800 # @@SKIP@@ http://www.ruby-lang.org
3801
3802
3803 # @@PLEAC@@_1.0
3804 string = '\n' # two characters, \ and an n
3805 string = 'Jon \'Maddog\' Orwant' # literal single quotes
3806
3807 string = "\n" # a "newline" character
3808 string = "Jon \"Maddog\" Orwant" # literal double quotes
3809
3810 string = %q/Jon 'Maddog' Orwant/ # literal single quotes
3811
3812 string = %q[Jon 'Maddog' Orwant] # literal single quotes
3813 string = %q{Jon 'Maddog' Orwant} # literal single quotes
3814 string = %q(Jon 'Maddog' Orwant) # literal single quotes
3815 string = %q<Jon 'Maddog' Orwant> # literal single quotes
3816
3817 a = <<"EOF"
3818 This is a multiline here document
3819 terminated by EOF on a line by itself
3820 EOF
3821
3822
3823 # @@PLEAC@@_1.1
3824 value = string[offset,count]
3825 value = string[offset..-1]
3826
3827 string[offset,count] = newstring
3828 string[offset..-1] = newtail
3829
3830 # in Ruby we can also specify intervals by their two offsets
3831 value = string[offset..offs2]
3832 string[offset..offs2] = newstring
3833
3834 leading, s1, s2, trailing = data.unpack("A5 x3 A8 A8 A*")
3835
3836 fivers = string.unpack("A5" * (string.length/5))
3837
3838 chars = string.unpack("A1" * string.length)
3839
3840 string = "This is what you have"
3841 # +012345678901234567890 Indexing forwards (left to right)
3842 # 109876543210987654321- Indexing backwards (right to left)
3843 # note that 0 means 10 or 20, etc. above
3844
3845 first = string[0, 1] # "T"
3846 start = string[5, 2] # "is"
3847 rest = string[13..-1] # "you have"
3848 last = string[-1, 1] # "e"
3849 end_ = string[-4..-1] # "have"
3850 piece = string[-8, 3] # "you"
3851
3852 string[5, 2] = "wasn't" # change "is" to "wasn't"
3853 string[-12..-1] = "ondrous" # "This wasn't wondrous"
3854 string[0, 1] = "" # delete first character
3855 string[-10..-1] = "" # delete last 10 characters
3856
3857 if string[-10..-1] =~ /pattern/
3858 puts "Pattern matches in last 10 characters"
3859 end
3860
3861 string[0, 5].gsub!(/is/, 'at')
3862
3863 a = "make a hat"
3864 a[0, 1], a[-1, 1] = a[-1, 1], a[0, 1]
3865
3866 a = "To be or not to be"
3867 b = a.unpack("x6 A6")
3868
3869 b, c = a.unpack("x6 A2 X5 A2")
3870 puts "#{b}\n#{c}\n"
3871
3872 def cut2fmt(*args)
3873 template = ''
3874 lastpos = 1
3875 for place in args
3876 template += "A" + (place - lastpos).to_s + " "
3877 lastpos = place
3878 end
3879 template += "A*"
3880 return template
3881 end
3882
3883 fmt = cut2fmt(8, 14, 20, 26, 30)
3884
3885
3886 # @@PLEAC@@_1.2
3887 # careful! "b is true" doesn't mean "b != 0" (0 is true in Ruby)
3888 # thus no problem of "defined" later since only nil is false
3889 # the following sets to `c' if `b' is nil or false
3890 a = b || c
3891
3892 # if you need Perl's behaviour (setting to `c' if `b' is 0) the most
3893 # effective way is to use Numeric#nonzero? (thanks to Dave Thomas!)
3894 a = b.nonzero? || c
3895
3896 # you will still want to use defined? in order to test
3897 # for scope existence of a given object
3898 a = defined?(b) ? b : c
3899
3900 dir = ARGV.shift || "/tmp"
3901
3902
3903 # @@PLEAC@@_1.3
3904 v1, v2 = v2, v1
3905
3906 alpha, beta, production = %w(January March August)
3907 alpha, beta, production = beta, production, alpha
3908
3909
3910 # @@PLEAC@@_1.4
3911 num = char[0]
3912 char = num.chr
3913
3914 # Ruby also supports having a char from character constant
3915 num = ?r
3916
3917 char = sprintf("%c", num)
3918 printf("Number %d is character %c\n", num, num)
3919
3920 ascii = string.unpack("C*")
3921 string = ascii.pack("C*")
3922
3923 hal = "HAL"
3924 ascii = hal.unpack("C*")
3925 # We can't use Array#each since we can't mutate a Fixnum
3926 ascii.collect! { |i|
3927 i + 1 # add one to each ASCII value
3928 }
3929 ibm = ascii.pack("C*")
3930 puts ibm
3931
3932
3933 # @@PLEAC@@_1.5
3934 array = string.split('')
3935
3936 array = string.unpack("C*")
3937
3938 string.scan(/./) { |b|
3939 # do something with b
3940 }
3941
3942 string = "an apple a day"
3943 print "unique chars are: ", string.split('').uniq.sort, "\n"
3944
3945 sum = 0
3946 for ascval in string.unpack("C*") # or use Array#each for a pure OO style :)
3947 sum += ascval
3948 end
3949 puts "sum is #{sum & 0xffffffff}" # since Ruby will go Bignum if necessary
3950
3951 # @@INCLUDE@@ include/ruby/slowcat.rb
3952
3953
3954 # @@PLEAC@@_1.6
3955 revbytes = string.reverse
3956
3957 revwords = string.split(" ").reverse.join(" ")
3958
3959 revwords = string.split(/(\s+)/).reverse.join
3960
3961 # using the fact that IO is Enumerable, you can directly "select" it
3962 long_palindromes = File.open("/usr/share/dict/words").
3963 select { |w| w.chomp!; w.reverse == w && w.length > 5 }
3964
3965
3966 # @@PLEAC@@_1.7
3967 while string.sub!("\t+") { ' ' * ($&.length * 8 - $`.length % 8) }
3968 end
3969
3970
3971 # @@PLEAC@@_1.8
3972 'You owe #{debt} to me'.gsub(/\#{(\w+)}/) { eval($1) }
3973
3974 rows, cols = 24, 80
3975 text = %q(I am #{rows} high and #{cols} long)
3976 text.gsub!(/\#{(\w+)}/) { eval("#{$1}") }
3977 puts text
3978
3979 'I am 17 years old'.gsub(/\d+/) { 2 * $&.to_i }
3980
3981
3982 # @@PLEAC@@_1.9
3983 e = "bo peep".upcase
3984 e.downcase!
3985 e.capitalize!
3986
3987 "thIS is a loNG liNE".gsub!(/\w+/) { $&.capitalize }
3988
3989
3990 # @@PLEAC@@_1.10
3991 "I have #{n+1} guanacos."
3992 print "I have ", n+1, " guanacos."
3993
3994
3995 # @@PLEAC@@_1.11
3996 var = <<'EOF'.gsub(/^\s+/, '')
3997 your text
3998 goes here
3999 EOF
4000
4001
4002 # @@PLEAC@@_1.12
4003 string = "Folding and splicing is the work of an editor,\n"+
4004 "not a mere collection of silicon\n"+
4005 "and\n"+
4006 "mobile electrons!"
4007
4008 def wrap(str, max_size)
4009 all = []
4010 line = ''
4011 for l in str.split
4012 if (line+l).length >= max_size
4013 all.push(line)
4014 line = ''
4015 end
4016 line += line == '' ? l : ' ' + l
4017 end
4018 all.push(line).join("\n")
4019 end
4020
4021 print wrap(string, 20)
4022 #=> Folding and
4023 #=> splicing is the
4024 #=> work of an editor,
4025 #=> not a mere
4026 #=> collection of
4027 #=> silicon and mobile
4028 #=> electrons!
4029
4030
4031 # @@PLEAC@@_1.13
4032 string = %q(Mom said, "Don't do that.")
4033 string.gsub(/['"]/) { '\\'+$& }
4034 string.gsub(/['"]/, '\&\&')
4035 string.gsub(/[^A-Z]/) { '\\'+$& }
4036 "is a test!".gsub(/\W/) { '\\'+$& } # no function like quotemeta?
4037
4038
4039 # @@PLEAC@@_1.14
4040 string.strip!
4041
4042
4043 # @@PLEAC@@_1.15
4044 def parse_csv(text)
4045 new = text.scan(/"([^\"\\]*(?:\\.[^\"\\]*)*)",?|([^,]+),?|,/)
4046 new << nil if text[-1] == ?,
4047 new.flatten.compact
4048 end
4049
4050 line = %q<XYZZY,"","O'Reilly, Inc","Wall, Larry","a \"glug\" bit,",5,"Error, Core Dumped">
4051 fields = parse_csv(line)
4052 fields.each_with_index { |v,i|
4053 print "#{i} : #{v}\n";
4054 }
4055
4056
4057 # @@PLEAC@@_1.16
4058 # Use the soundex.rb Library from Michael Neumann.
4059 # http://www.s-direktnet.de/homepages/neumann/rb_prgs/Soundex.rb
4060 require 'Soundex'
4061
4062 code = Text::Soundex.soundex(string)
4063 codes = Text::Soundex.soundex(array)
4064
4065 # substitution function for getpwent():
4066 # returns an array of user entries,
4067 # each entry contains the username and the full name
4068 def login_names
4069 result = []
4070 File.open("/etc/passwd") { |file|
4071 file.each_line { |line|
4072 next if line.match(/^#/)
4073 cols = line.split(":")
4074 result.push([cols[0], cols[4]])
4075 }
4076 }
4077 result
4078 end
4079
4080 puts "Lookup user: "
4081 user = STDIN.gets
4082 user.chomp!
4083 exit unless user
4084 name_code = Text::Soundex.soundex(user)
4085
4086 splitter = Regexp.new('(\w+)[^,]*\b(\w+)')
4087 for username, fullname in login_names do
4088 firstname, lastname = splitter.match(fullname)[1,2]
4089 if name_code == Text::Soundex.soundex(username)
4090 || name_code == Text::Soundex.soundex(firstname)
4091 || name_code == Text::Soundex.soundex(lastname)
4092 then
4093 puts "#{username}: #{firstname} #{lastname}"
4094 end
4095 end
4096
4097
4098 # @@PLEAC@@_1.17
4099 # @@INCLUDE@@ include/ruby/fixstyle.rb
4100
4101
4102 # @@PLEAC@@_1.18
4103 # @@INCLUDE@@ include/ruby/psgrep.rb
4104
4105
4106 # @@PLEAC@@_2.1
4107 # Matz tells that you can use Integer() for strict checked conversion.
4108 Integer("abc")
4109 #=> `Integer': invalid value for Integer: "abc" (ArgumentError)
4110 Integer("567")
4111 #=> 567
4112
4113 # You may use Float() for floating point stuff
4114 Integer("56.7")
4115 #=> `Integer': invalid value for Integer: "56.7" (ArgumentError)
4116 Float("56.7")
4117 #=> 56.7
4118
4119 # You may also use a regexp for that
4120 if string =~ /^[+-]?\d+$/
4121 p 'is an integer'
4122 else
4123 p 'is not'
4124 end
4125
4126 if string =~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/
4127 p 'is a decimal number'
4128 else
4129 p 'is not'
4130 end
4131
4132
4133 # @@PLEAC@@_2.2
4134 # equal(num1, num2, accuracy) : returns true if num1 and num2 are
4135 # equal to accuracy number of decimal places
4136 def equal(i, j, a)
4137 sprintf("%.#{a}g", i) == sprintf("%.#{a}g", j)
4138 end
4139
4140 wage = 536 # $5.36/hour
4141 week = 40 * wage # $214.40
4142 printf("One week's wage is: \$%.2f\n", week/100.0)
4143
4144
4145 # @@PLEAC@@_2.3
4146 num.round # rounds to integer
4147
4148 a = 0.255
4149 b = sprintf("%.2f", a)
4150 print "Unrounded: #{a}\nRounded: #{b}\n"
4151 printf "Unrounded: #{a}\nRounded: %.2f\n", a
4152
4153 print "number\tint\tfloor\tceil\n"
4154 a = [ 3.3 , 3.5 , 3.7, -3.3 ]
4155 for n in a
4156 printf("% .1f\t% .1f\t% .1f\t% .1f\n", # at least I don't fake my output :)
4157 n, n.to_i, n.floor, n.ceil)
4158 end
4159
4160
4161 # @@PLEAC@@_2.4
4162 def dec2bin(n)
4163 [n].pack("N").unpack("B32")[0].sub(/^0+(?=\d)/, '')
4164 end
4165
4166 def bin2dec(n)
4167 [("0"*32+n.to_s)[-32..-1]].pack("B32").unpack("N")[0]
4168 end
4169
4170
4171 # @@PLEAC@@_2.5
4172 for i in x .. y
4173 # i is set to every integer from x to y, inclusive
4174 end
4175
4176 x.step(y,7) { |i|
4177 # i is set to every integer from x to y, stepsize = 7
4178 }
4179
4180 print "Infancy is: "
4181 (0..2).each { |i|
4182 print i, " "
4183 }
4184 print "\n"
4185
4186
4187 # @@PLEAC@@_2.6
4188 # We can add conversion methods to the Integer class,
4189 # this makes a roman number just a representation for normal numbers.
4190 class Integer
4191
4192 @@romanlist = [["M", 1000],
4193 ["CM", 900],
4194 ["D", 500],
4195 ["CD", 400],
4196 ["C", 100],
4197 ["XC", 90],
4198 ["L", 50],
4199 ["XL", 40],
4200 ["X", 10],
4201 ["IX", 9],
4202 ["V", 5],
4203 ["IV", 4],
4204 ["I", 1]]
4205
4206 def to_roman
4207 remains = self
4208 roman = ""
4209 for sym, num in @@romanlist
4210 while remains >= num
4211 remains -= num
4212 roman << sym
4213 end
4214 end
4215 roman
4216 end
4217
4218 def Integer.from_roman(roman)
4219 ustr = roman.upcase
4220 sum = 0
4221 for entry in @@romanlist
4222 sym, num = entry[0], entry[1]
4223 while sym == ustr[0, sym.length]
4224 sum += num
4225 ustr.slice!(0, sym.length)
4226 end
4227 end
4228 sum
4229 end
4230
4231 end
4232
4233
4234 roman_fifteen = 15.to_roman
4235 puts "Roman for fifteen is #{roman_fifteen}"
4236 i = Integer.from_roman(roman_fifteen)
4237 puts "Converted back, #{roman_fifteen} is #{i}"
4238
4239 # check
4240 for i in (1..3900)
4241 r = i.to_roman
4242 j = Integer.from_roman(r)
4243 if i != j
4244 puts "error: #{i} : #{r} - #{j}"
4245 end
4246 end
4247
4248
4249 # @@PLEAC@@_2.7
4250 random = rand(y-x+1)+x
4251
4252 chars = ["A".."Z","a".."z","0".."9"].collect { |r| r.to_a }.join + %q(!@$%^&*)
4253 password = (1..8).collect { chars[rand(chars.size)] }.pack("C*")
4254
4255
4256 # @@PLEAC@@_2.8
4257 srand # uses a combination of the time, the process id, and a sequence number
4258 srand(val) # for repeatable behaviour
4259
4260
4261 # @@PLEAC@@_2.9
4262 # from the randomr lib:
4263 # http://raa.ruby-lang.org/project/randomr/
4264 ----> http://raa.ruby-lang.org/project/randomr/
4265
4266 require 'random/mersenne_twister'
4267 mers = Random::MersenneTwister.new 123456789
4268 puts mers.rand(0) # 0.550321932544541
4269 puts mers.rand(10) # 2
4270
4271 # using online sources of random data via the realrand package:
4272 # http://raa.ruby-lang.org/project/realrand/
4273 # **Note**
4274 # The following online services are used in this package:
4275 # http://www.random.org - source: atmospheric noise
4276 # http://www.fourmilab.ch/hotbits - source: radioactive decay timings
4277 # http://random.hd.org - source: entropy from local and network noise
4278 # Please visit the sites and respect the rules of each service.
4279
4280 require 'random/online'
4281
4282 generator1 = Random::RandomOrg.new
4283 puts generator1.randbyte(5).join(",")
4284 puts generator1.randnum(10, 1, 6).join(",") # Roll dice 10 times.
4285
4286 generator2 = Random::FourmiLab.new
4287 puts generator2.randbyte(5).join(",")
4288 # randnum is not supported.
4289
4290 generator3 = Random::EntropyPool.new
4291 puts generator3.randbyte(5).join(",")
4292 # randnum is not supported.
4293
4294
4295 # @@PLEAC@@_2.10
4296 def gaussian_rand
4297 begin
4298 u1 = 2 * rand() - 1
4299 u2 = 2 * rand() - 1
4300 w = u1*u1 + u2*u2
4301 end while (w >= 1)
4302 w = Math.sqrt((-2*Math.log(w))/w)
4303 [ u2*w, u1*w ]
4304 end
4305
4306 mean = 25
4307 sdev = 2
4308 salary = gaussian_rand[0] * sdev + mean
4309 printf("You have been hired at \$%.2f\n", salary)
4310
4311
4312 # @@PLEAC@@_2.11
4313 def deg2rad(d)
4314 (d/180.0)*Math::PI
4315 end
4316
4317 def rad2deg(r)
4318 (r/Math::PI)*180
4319 end
4320
4321
4322 # @@PLEAC@@_2.12
4323 sin_val = Math.sin(angle)
4324 cos_val = Math.cos(angle)
4325 tan_val = Math.tan(angle)
4326
4327 # AFAIK Ruby's Math module doesn't provide acos/asin
4328 # While we're at it, let's also define missing hyperbolic functions
4329 module Math
4330 def Math.asin(x)
4331 atan2(x, sqrt(1 - x**2))
4332 end
4333 def Math.acos(x)
4334 atan2(sqrt(1 - x**2), x)
4335 end
4336 def Math.atan(x)
4337 atan2(x, 1)
4338 end
4339 def Math.sinh(x)
4340 (exp(x) - exp(-x)) / 2
4341 end
4342 def Math.cosh(x)
4343 (exp(x) + exp(-x)) / 2
4344 end
4345 def Math.tanh(x)
4346 sinh(x) / cosh(x)
4347 end
4348 end
4349
4350 # The support for Complex numbers is not built-in
4351 y = Math.acos(3.7)
4352 #=> in `sqrt': square root for negative number (ArgumentError)
4353
4354 # There is an implementation of Complex numbers in 'complex.rb' in current
4355 # Ruby distro, but it doesn't support atan2 with complex args, so it doesn't
4356 # solve this problem.
4357
4358
4359 # @@PLEAC@@_2.13
4360 log_e = Math.log(val)
4361 log_10 = Math.log10(val)
4362
4363 def log_base(base, val)
4364 Math.log(val)/Math.log(base)
4365 end
4366
4367 answer = log_base(10, 10_000)
4368 puts "log10(10,000) = #{answer}"
4369
4370
4371 # @@PLEAC@@_2.14
4372 require 'matrix.rb'
4373
4374 a = Matrix[[3, 2, 3], [5, 9, 8]]
4375 b = Matrix[[4, 7], [9, 3], [8, 1]]
4376 c = a * b
4377
4378 a.row_size
4379 a.column_size
4380
4381 c.det
4382 a.transpose
4383
4384
4385 # @@PLEAC@@_2.15
4386 require 'complex.rb'
4387 require 'rational.rb'
4388
4389 a = Complex(3, 5) # 3 + 5i
4390 b = Complex(2, -2) # 2 - 2i
4391 puts "c = #{a*b}"
4392
4393 c = a * b
4394 d = 3 + 4*Complex::I
4395
4396 printf "sqrt(#{d}) = %s\n", Math.sqrt(d)
4397
4398
4399 # @@PLEAC@@_2.16
4400 number = hexadecimal.hex
4401 number = octal.oct
4402
4403 print "Gimme a number in decimal, octal, or hex: "
4404 num = gets.chomp
4405 exit unless defined?(num)
4406 num = num.oct if num =~ /^0/ # does both oct and hex
4407 printf "%d %x %o\n", num, num, num
4408
4409 print "Enter file permission in octal: "
4410 permissions = gets.chomp
4411 raise "Exiting ...\n" unless defined?(permissions)
4412 puts "The decimal value is #{permissions.oct}"
4413
4414
4415 # @@PLEAC@@_2.17
4416 def commify(n)
4417 n.to_s =~ /([^\.]*)(\..*)?/
4418 int, dec = $1.reverse, $2 ? $2 : ""
4419 while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
4420 end
4421 int.reverse + dec
4422 end
4423
4424
4425 # @@PLEAC@@_2.18
4426 printf "It took %d hour%s\n", time, time == 1 ? "" : "s"
4427
4428 # dunno if an equivalent to Lingua::EN::Inflect exists...
4429
4430
4431 # @@PLEAC@@_2.19
4432 #-----------------------------
4433 #!/usr/bin/ruby
4434 # bigfact - calculating prime factors
4435 def factorize(orig)
4436 factors = {}
4437 factors.default = 0 # return 0 instead nil if key not found in hash
4438 n = orig
4439 i = 2
4440 sqi = 4 # square of i
4441 while sqi <= n do
4442 while n.modulo(i) == 0 do
4443 n /= i
4444 factors[i] += 1
4445 # puts "Found factor #{i}"
4446 end
4447 # we take advantage of the fact that (i +1)**2 = i**2 + 2*i +1
4448 sqi += 2 * i + 1
4449 i += 1
4450 end
4451
4452 if (n != 1) && (n != orig)
4453 factors[n] += 1
4454 end
4455 factors
4456 end
4457
4458 def printfactorhash(orig, factorcount)
4459 print format("%-10d ", orig)
4460 if factorcount.length == 0
4461 print "PRIME"
4462 else
4463 # sorts after number, because the hash keys are numbers
4464 factorcount.sort.each { |factor,exponent|
4465 print factor
4466 if exponent > 1
4467 print "**", exponent
4468 end
4469 print " "
4470 }
4471 end
4472 puts
4473 end
4474
4475 for arg in ARGV
4476 n = arg.to_i
4477 mfactors = factorize(n)
4478 printfactorhash(n, mfactors)
4479 end
4480 #-----------------------------
4481
4482
4483 # @@PLEAC@@_3.0
4484 puts Time.now
4485
4486 print "Today is day ", Time.now.yday, " of the current year.\n"
4487 print "Today is day ", Time.now.day, " of the current month.\n"
4488
4489
4490 # @@PLEAC@@_3.1
4491 day, month, year = Time.now.day, Time.now.month, Time.now.year
4492 # or
4493 day, month, year = Time.now.to_a[3..5]
4494
4495 tl = Time.now.localtime
4496 printf("The current date is %04d %02d %02d\n", tl.year, tl.month, tl.day)
4497
4498 Time.now.localtime.strftime("%Y-%m-%d")
4499
4500
4501 # @@PLEAC@@_3.2
4502 Time.local(year, month, day, hour, minute, second).tv_sec
4503 Time.gm(year, month, day, hour, minute, second).tv_sec
4504
4505
4506 # @@PLEAC@@_3.3
4507 sec, min, hour, day, month, year, wday, yday, isdst, zone = Time.at(epoch_secs).to_a
4508
4509
4510 # @@PLEAC@@_3.4
4511 when_ = now + difference # now -> Time ; difference -> Numeric (delta in seconds)
4512 then_ = now - difference
4513
4514
4515 # @@PLEAC@@_3.5
4516 bree = 361535725
4517 nat = 96201950
4518
4519 difference = bree - nat
4520 puts "There were #{difference} seconds between Nat and Bree"
4521
4522 seconds = difference % 60
4523 difference = (difference - seconds) / 60
4524 minutes = difference % 60
4525 difference = (difference - minutes) / 60
4526 hours = difference % 24
4527 difference = (difference - hours) / 24
4528 days = difference % 7
4529 weeks = (difference - days) / 7
4530
4531 puts "(#{weeks} weeks, #{days} days, #{hours}:#{minutes}:#{seconds})"
4532
4533
4534 # @@PLEAC@@_3.6
4535 monthday, weekday, yearday = date.mday, date.wday, date.yday
4536
4537 # AFAIK the week number is not just a division since week boundaries are on sundays
4538 weeknum = d.strftime("%U").to_i + 1
4539
4540 year = 1981
4541 month = "jun" # or `6' if you want to emulate a broken language
4542 day = 16
4543 t = Time.mktime(year, month, day)
4544 print "#{month}/#{day}/#{year} was a ", t.strftime("%A"), "\n"
4545
4546
4547 # @@PLEAC@@_3.7
4548 yyyy, mm, dd = $1, $2, $3 if "1998-06-25" =~ /(\d+)-(\d+)-(\d+)/
4549
4550 epoch_seconds = Time.mktime(yyyy, mm, dd).tv_sec
4551
4552 # dunno an equivalent to Date::Manip#ParseDate
4553
4554
4555 # @@PLEAC@@_3.8
4556 string = Time.at(epoch_secs)
4557 Time.at(1234567890).gmtime # gives: Fri Feb 13 23:31:30 UTC 2009
4558
4559 time = Time.mktime(1973, "jan", 18, 3, 45, 50)
4560 print "In localtime it gives: ", time.localtime, "\n"
4561
4562
4563 # @@PLEAC@@_3.9
4564 # Ruby provides micro-seconds in Time object
4565 Time.now.usec
4566
4567 # Ruby gives the seconds in floating format when substracting two Time objects
4568 before = Time.now
4569 line = gets
4570 elapsed = Time.now - before
4571 puts "You took #{elapsed} seconds."
4572
4573 # On my Celeron-400 with Linux-2.2.19-14mdk, average for three execs are:
4574 # This Ruby version: average 0.00321 sec
4575 # Cookbook's Perl version: average 0.00981 sec
4576 size = 500
4577 number_of_times = 100
4578 total_time = 0
4579 number_of_times.times {
4580 # populate array
4581 array = []
4582 size.times { array << rand }
4583 # sort it
4584 begin_ = Time.now
4585 array.sort!
4586 time = Time.now - begin_
4587 total_time += time
4588 }
4589 printf "On average, sorting %d random numbers takes %.5f seconds\n",
4590 size, (total_time/Float(number_of_times))
4591
4592
4593 # @@PLEAC@@_3.10
4594 sleep(0.005) # Ruby is definitely not as broken as Perl :)
4595 # (may be interrupted by sending the process a SIGALRM)
4596
4597
4598 # @@PLEAC@@_3.11
4599 #!/usr/bin/ruby -w
4600 # hopdelta - feed mail header, produce lines
4601 # showing delay at each hop.
4602 require 'time'
4603 class MailHopDelta
4604
4605 def initialize(mail)
4606 @head = mail.gsub(/\n\s+/,' ')
4607 @topline = %w-Sender Recipient Time Delta-
4608 @start_from = mail.match(/^From.*\@([^\s>]*)/)[1]
4609 @date = Time.parse(mail.match(/^Date:\s+(.*)/)[1])
4610 end
4611
4612 def out(line)
4613 "%-20.20s %-20.20s %-20.20s %s" % line
4614 end
4615
4616 def hop_date(day)
4617 day.strftime("%I:%M:%S %Y/%m/%d")
4618 end
4619
4620 def puts_hops
4621 puts out(@topline)
4622 puts out(['Start', @start_from, hop_date(@date),''])
4623 @head.split(/\n/).reverse.grep(/^Received:/).each do |hop|
4624 hop.gsub!(/\bon (.*?) (id.*)/,'; \1')
4625 whence = hop.match(/;\s+(.*)$/)[1]
4626 unless whence
4627 warn "Bad received line: #{hop}"
4628 next
4629 end
4630 from = $+ if hop =~ /from\s+(\S+)|\((.*?)\)/
4631 by = $1 if hop =~ /by\s+(\S+\.\S+)/
4632 next unless now = Time.parse(whence).localtime
4633 delta = now - @date
4634 puts out([from, by, hop_date(now), hop_time(delta)])
4635 @date = now
4636 end
4637 end
4638
4639 def hop_time(secs)
4640 sign = secs < 0 ? -1 : 1
4641 days, secs = secs.abs.divmod(60 * 60 * 24)
4642 hours,secs = secs.abs.divmod(60 * 60)
4643 mins, secs = secs.abs.divmod(60)
4644 rtn = "%3ds" % [secs * sign]
4645 rtn << "%3dm" % [mins * sign] if mins != 0
4646 rtn << "%3dh" % [hours * sign] if hours != 0
4647 rtn << "%3dd" % [days * sign] if days != 0
4648 rtn
4649 end
4650 end
4651
4652 $/ = ""
4653 mail = MailHopDelta.new(ARGF.gets).puts_hops
4654
4655
4656 # @@PLEAC@@_4.0
4657 single_level = [ "this", "that", "the", "other" ]
4658
4659 # Ruby directly supports nested arrays
4660 double_level = [ "this", "that", [ "the", "other" ] ]
4661 still_single_level = [ "this", "that", [ "the", "other" ] ].flatten
4662
4663
4664 # @@PLEAC@@_4.1
4665 a = [ "quick", "brown", "fox" ]
4666 a = %w(Why are you teasing me?)
4667
4668 lines = <<"END_OF_HERE_DOC".gsub(/^\s*(.+)/, '\1')
4669 The boy stood on the burning deck,
4670 It was as hot as glass.
4671 END_OF_HERE_DOC
4672
4673 bigarray = IO.readlines("mydatafile").collect { |l| l.chomp }
4674
4675 name = "Gandalf"
4676 banner = %Q(Speak, #{name}, and welcome!)
4677
4678 host_info = `host #{his_host}`
4679
4680 %x(ps #{$$})
4681
4682 banner = 'Costs only $4.95'.split(' ')
4683
4684 rax = %w! ( ) < > { } [ ] !
4685
4686
4687 # @@PLEAC@@_4.2
4688 def commify_series(a)
4689 a.size == 0 ? '' :
4690 a.size == 1 ? a[0] :
4691 a.size == 2 ? a.join(' and ') :
4692 a[0..-2].join(', ') + ', and ' + a[-1]
4693 end
4694
4695 array = [ "red", "yellow", "green" ]
4696
4697 print "I have ", array, " marbles\n"
4698 # -> I have redyellowgreen marbles
4699
4700 # But unlike Perl:
4701 print "I have #{array} marbles\n"
4702 # -> I have redyellowgreen marbles
4703 # So, needs:
4704 print "I have #{array.join(' ')} marbles\n"
4705 # -> I have red yellow green marbles
4706
4707 def commify_series(a)
4708 sepchar = a.select { |p| p =~ /,/ } != [] ? '; ' : ', '
4709 a.size == 0 ? '' :
4710 a.size == 1 ? a[0] :
4711 a.size == 2 ? a.join(' and ') :
4712 a[0..-2].join(sepchar) + sepchar + 'and ' + a[-1]
4713 end
4714
4715
4716 # @@PLEAC@@_4.3
4717 # (note: AFAIK Ruby doesn't allow gory change of Array length)
4718 # grow the array by assigning nil to past the end of array
4719 ary[new_size-1] = nil
4720 # shrink the array by slicing it down
4721 ary.slice!(new_size..-1)
4722 # init the array with given size
4723 Array.new(number_of_elems)
4724 # assign to an element past the original end enlarges the array
4725 ary[index_new_last_elem] = value
4726
4727 def what_about_that_array(a)
4728 print "The array now has ", a.size, " elements.\n"
4729 # Index of last element is not really interesting in Ruby
4730 print "Element #3 is `#{a[3]}'.\n"
4731 end
4732 people = %w(Crosby Stills Nash Young)
4733 what_about_that_array(people)
4734
4735
4736 # @@PLEAC@@_4.4
4737 # OO style
4738 bad_users.each { |user|
4739 complain(user)
4740 }
4741 # or, functional style
4742 for user in bad_users
4743 complain(user)
4744 end
4745
4746 for var in ENV.keys.sort
4747 puts "#{var}=#{ENV[var]}"
4748 end
4749
4750 for user in all_users
4751 disk_space = get_usage(user)
4752 if (disk_space > MAX_QUOTA)
4753 complain(user)
4754 end
4755 end
4756
4757 for l in IO.popen("who").readlines
4758 print l if l =~ /^gc/
4759 end
4760
4761 # we can mimic the obfuscated Perl way
4762 while fh.gets # $_ is set to the line just read
4763 chomp # $_ has a trailing \n removed, if it had one
4764 split.each { |w| # $_ is split on whitespace
4765 # but $_ is not set to each chunk as in Perl
4766 print w.reverse
4767 }
4768 end
4769 # ...or use a cleaner way
4770 for l in fh.readlines
4771 l.chomp.split.each { |w| print w.reverse }
4772 end
4773
4774 # same drawback as in problem 1.4, we can't mutate a Numeric...
4775 array.collect! { |v| v - 1 }
4776
4777 a = [ .5, 3 ]; b = [ 0, 1 ]
4778 for ary in [ a, b ]
4779 ary.collect! { |v| v * 7 }
4780 end
4781 puts "#{a.join(' ')} #{b.join(' ')}"
4782
4783 # we can mutate Strings, cool; we need a trick for the scalar
4784 for ary in [ [ scalar ], array, hash.values ]
4785 ary.each { |v| v.strip! } # String#strip rules :)
4786 end
4787
4788
4789 # @@PLEAC@@_4.5
4790 # not relevant in Ruby since we have always references
4791 for item in array
4792 # do somethingh with item
4793 end
4794
4795
4796 # @@PLEAC@@_4.6
4797 unique = list.uniq
4798
4799 # generate a list of users logged in, removing duplicates
4800 users = `who`.collect { |l| l =~ /(\w+)/; $1 }.sort.uniq
4801 puts("users logged in: #{commify_series(users)}") # see 4.2 for commify_series
4802
4803
4804 # @@PLEAC@@_4.7
4805 a - b
4806 # [ 1, 1, 2, 2, 3, 3, 3, 4, 5 ] - [ 1, 2, 4 ] -> [3, 5]
4807
4808
4809 # @@PLEAC@@_4.8
4810 union = a | b
4811 intersection = a & b
4812 difference = a - b
4813
4814
4815 # @@PLEAC@@_4.9
4816 array1.concat(array2)
4817 # if you will assign to another object, better use:
4818 new_ary = array1 + array2
4819
4820 members = [ "Time", "Flies" ]
4821 initiates = [ "An", "Arrow" ]
4822 members += initiates
4823
4824 members = [ "Time", "Flies" ]
4825 initiates = [ "An", "Arrow" ]
4826 members[2,0] = [ "Like", initiates ].flatten
4827
4828 members[0] = "Fruit"
4829 members[3,2] = "A", "Banana"
4830
4831
4832 # @@PLEAC@@_4.10
4833 reversed = ary.reverse
4834
4835 ary.reverse_each { |e|
4836 # do something with e
4837 }
4838
4839 descending = ary.sort.reverse
4840 descending = ary.sort { |a,b| b <=> a }
4841
4842
4843 # @@PLEAC@@_4.11
4844 # remove n elements from front of ary (shift n)
4845 front = ary.slice!(0, n)
4846
4847 # remove n elements from the end of ary (pop n)
4848 end_ = ary.slice!(-n .. -1)
4849
4850 # let's extend the Array class, to make that useful
4851 class Array
4852 def shift2()
4853 slice!(0 .. 1) # more symetric with pop2...
4854 end
4855 def pop2()
4856 slice!(-2 .. -1)
4857 end
4858 end
4859
4860 friends = %w(Peter Paul Mary Jim Tim)
4861 this, that = friends.shift2
4862
4863 beverages = %w(Dew Jolt Cola Sprite Fresca)
4864 pair = beverages.pop2
4865
4866
4867 # @@PLEAC@@_4.12
4868 # use Enumerable#detect (or the synonym Enumerable#find)
4869 highest_eng = employees.detect { |emp| emp.category == 'engineer' }
4870
4871
4872 # @@PLEAC@@_4.13
4873 # use Enumerable#select (or the synonym Enumerable#find_all)
4874 bigs = nums.select { |i| i > 1_000_000 }
4875 pigs = users.keys.select { |k| users[k] > 1e7 }
4876
4877 matching = `who`.select { |u| u =~ /^gnat / }
4878
4879 engineers = employees.select { |e| e.position == 'Engineer' }
4880
4881 secondary_assistance = applicants.select { |a|
4882 a.income >= 26_000 && a.income < 30_000
4883 }
4884
4885
4886 # @@PLEAC@@_4.14
4887 # normally you would have an array of Numeric (Float or
4888 # Fixnum or Bignum), so you would use:
4889 sorted = unsorted.sort
4890 # if you have strings representing Integers or Floats
4891 # you may specify another sort method:
4892 sorted = unsorted.sort { |a,b| a.to_f <=> b.to_f }
4893
4894 # let's use the list of my own PID's
4895 `ps ux`.split("\n")[1..-1].
4896 select { |i| i =~ /^#{ENV['USER']}/ }.
4897 collect { |i| i.split[1] }.
4898 sort { |a,b| a.to_i <=> b.to_i }.each { |i| puts i }
4899 puts "Select a process ID to kill:"
4900 pid = gets.chomp
4901 raise "Exiting ... \n" unless pid && pid =~ /^\d+$/
4902 Process.kill('TERM', pid.to_i)
4903 sleep 2
4904 Process.kill('KILL', pid.to_i)
4905
4906 descending = unsorted.sort { |a,b| b.to_f <=> a.to_f }
4907
4908
4909 # @@PLEAC@@_4.15
4910 ordered = unordered.sort { |a,b| compare(a,b) }
4911
4912 precomputed = unordered.collect { |e| [compute, e] }
4913 ordered_precomputed = precomputed.sort { |a,b| a[0] <=> b[0] }
4914 ordered = ordered_precomputed.collect { |e| e[1] }
4915
4916 ordered = unordered.collect { |e| [compute, e] }.
4917 sort { |a,b| a[0] <=> b[0] }.
4918 collect { |e| e[1] }
4919
4920 for employee in employees.sort { |a,b| a.name <=> b.name }
4921 print employee.name, " earns \$ ", employee.salary, "\n"
4922 end
4923
4924 # Beware! `0' is true in Ruby.
4925 # For chaining comparisons, you may use Numeric#nonzero?, which
4926 # returns num if num is not zero, nil otherwise
4927 sorted = employees.sort { |a,b| (a.name <=> b.name).nonzero? || b.age <=> a.age }
4928
4929 users = []
4930 # getpwent is not wrapped in Ruby... let's fallback
4931 IO.readlines('/etc/passwd').each { |u| users << u.split(':') }
4932 users.sort! { |a,b| a[0] <=> b[0] }
4933 for user in users
4934 puts user[0]
4935 end
4936
4937 sorted = names.sort { |a,b| a[1, 1] <=> b[1, 1] }
4938 sorted = strings.sort { |a,b| a.length <=> b.length }
4939
4940 # let's show only the compact version
4941 ordered = strings.collect { |e| [e.length, e] }.
4942 sort { |a,b| a[0] <=> b[0] }.
4943 collect { |e| e[1] }
4944
4945 ordered = strings.collect { |e| [/\d+/.match(e)[0].to_i, e] }.
4946 sort { |a,b| a[0] <=> b[0] }.
4947 collect { |e| e[1] }
4948
4949 print `cat /etc/passwd`.collect { |e| [e, e.split(':').indexes(3,2,0)].flatten }.
4950 sort { |a,b| (a[1] <=> b[1]).nonzero? || (a[2] <=> b[2]).nonzero? || a[3] <=> b[3] }.
4951 collect { |e| e[0] }
4952
4953
4954 # @@PLEAC@@_4.16
4955 circular.unshift(circular.pop) # the last shall be first
4956 circular.push(circular.shift) # and vice versa
4957
4958 def grab_and_rotate(l)
4959 l.push(ret = l.shift)
4960 ret
4961 end
4962
4963 processes = [1, 2, 3, 4, 5]
4964 while (1)
4965 process = grab_and_rotate(processes)
4966 puts "Handling process #{process}"
4967 sleep 1
4968 end
4969
4970
4971 # @@PLEAC@@_4.17
4972 def fisher_yates_shuffle(a)
4973 (a.size-1).downto(1) { |i|
4974 j = rand(i+1)
4975 a[i], a[j] = a[j], a[i] if i != j
4976 }
4977 end
4978
4979 def naive_shuffle(a)
4980 for i in 0...a.size
4981 j = rand(a.size)
4982 a[i], a[j] = a[j], a[i]
4983 end
4984 end
4985
4986
4987 # @@PLEAC@@_4.18
4988 #!/usr/bin/env ruby
4989 # example 4-2 words
4990 # words - gather lines, present in colums
4991
4992 # class to encapsulate the word formatting from the input
4993 class WordFormatter
4994 def initialize(cols)
4995 @cols = cols
4996 end
4997
4998 # helper to return the length of the longest word in the wordlist
4999 def maxlen(wordlist)
5000 max = 1
5001 for word in wordlist
5002 if word.length > max
5003 max = word.length
5004 end
5005 end
5006 max
5007 end
5008
5009 # process the wordlist and print it formmated into columns
5010 def output(wordlist)
5011 collen = maxlen(wordlist) + 1
5012 columns = @cols / collen
5013 columns = 1 if columns == 0
5014 rows = (wordlist.length + columns - 1) / columns
5015 # now process each item, picking out proper piece for this position
5016 0.upto(rows * columns - 1) { |item|
5017 target = (item % columns) * rows + (item / columns)
5018 eol = ((item+1) % columns == 0)
5019 piece = wordlist[target] || ""
5020 piece = piece.ljust(collen) unless eol
5021 print piece
5022 puts if eol
5023 }
5024 # no need to finish it up, because eol is always true for the last element
5025 end
5026 end
5027
5028 # get nr of chars that fit in window or console, see PLEAC 15.4
5029 # not portable -- linux only (?)
5030 def getWinCharWidth()
5031 buf = "\0" * 8
5032 $stdout.ioctl(0x5413, buf)
5033 ws_row, ws_col, ws_xpixel, ws_ypixel = buf.unpack("$4")
5034 ws_col || 80
5035 rescue
5036 80
5037 end
5038
5039 # main program
5040 cols = getWinCharWidth()
5041 formatter = WordFormatter.new(cols)
5042 words = readlines()
5043 words.collect! { |line|
5044 line.chomp
5045 }
5046 formatter.output(words)
5047
5048
5049 # @@PLEAC@@_4.19
5050 # In ruby, Fixnum's are automatically converted to Bignum's when
5051 # needed, so there is no need for an extra module
5052 def factorial(n)
5053 s = 1
5054 while n > 0
5055 s *= n
5056 n -= 1
5057 end
5058 s
5059 end
5060
5061 puts factorial(500)
5062
5063 #---------------------------------------------------------
5064 # Example 4-3. tsc-permute
5065 # tsc_permute: permute each word of input
5066 def permute(items, perms)
5067 unless items.length > 0
5068 puts perms.join(" ")
5069 else
5070 for i in items
5071 newitems = items.dup
5072 newperms = perms.dup
5073 newperms.unshift(newitems.delete(i))
5074 permute(newitems, newperms)
5075 end
5076 end
5077 end
5078 # In ruby the main program must be after all definitions it is using
5079 permute(ARGV, [])
5080
5081 #---------------------------------------------------------
5082 # mjd_permute: permute each word of input
5083
5084 def factorial(n)
5085 s = 1
5086 while n > 0
5087 s *= n
5088 n -= 1
5089 end
5090 s
5091 end
5092
5093 # we use a class with a class variable store the private cache
5094 # for the results of the factorial function.
5095 class Factorial
5096 @@fact = [ 1 ]
5097 def Factorial.compute(n)
5098 if @@fact[n]
5099 @@fact[n]
5100 else
5101 @@fact[n] = n * Factorial.compute(n - 1)
5102 end
5103 end
5104 end
5105
5106 #---------------------------------------------------------
5107 # Example 4-4- mjd-permute
5108 # n2pat(n, len): produce the N-th pattern of length len
5109
5110 # We must use a lower case letter as parameter N, otherwise it is
5111 # handled as constant Length is the length of the resulting
5112 # array, not the index of the last element (length -1) like in
5113 # the perl example.
5114 def n2pat(n, length)
5115 pat = []
5116 i = 1
5117 while i <= length
5118 pat.push(n % i)
5119 n /= i
5120 i += 1
5121 end
5122 pat
5123 end
5124
5125 # pat2perm(pat): turn pattern returned by n2pat() into
5126 # permutation of integers.
5127 def pat2perm(pat)
5128 source = (0 .. pat.length - 1).to_a
5129 perm = []
5130 perm.push(source.slice!(pat.pop)) while pat.length > 0
5131 perm
5132 end
5133
5134 def n2perm(n, len)
5135 pat2perm(n2pat(n,len))
5136 end
5137
5138 # In ruby the main program must be after all definitions
5139 while gets
5140 data = split
5141 # the perl solution has used $#data, which is length-1
5142 num_permutations = Factorial.compute(data.length())
5143 0.upto(num_permutations - 1) do |i|
5144 # in ruby we can not use an array as selector for an array
5145 # but by exchanging the two arrays, we can use the collect method
5146 # which returns an array with the result of all block invocations
5147 permutation = n2perm(i, data.length).collect {
5148 |j| data[j]
5149 }
5150 puts permutation.join(" ")
5151 end
5152 end
5153
5154
5155 # @@PLEAC@@_5.0
5156 age = { "Nat", 24,
5157 "Jules", 25,
5158 "Josh", 17 }
5159
5160 age["Nat"] = 24
5161 age["Jules"] = 25
5162 age["Josh"] = 17
5163
5164 food_color = {
5165 "Apple" => "red",
5166 "Banana" => "yellow",
5167 "Lemon" => "yellow",
5168 "Carrot" => "orange"
5169 }
5170
5171 # In Ruby, you cannot avoid the double or simple quoting
5172 # while manipulatin hashes
5173
5174
5175 # @@PLEAC@@_5.1
5176 hash[key] = value
5177
5178 food_color["Raspberry"] = "pink"
5179 puts "Known foods:", food_color.keys
5180
5181
5182 # @@PLEAC@@_5.2
5183 # does hash have a value for key ?
5184 if (hash.has_key?(key))
5185 # it exists
5186 else
5187 # it doesn't
5188 end
5189
5190 [ "Banana", "Martini" ].each { |name|
5191 print name, " is a ", food_color.has_key?(name) ? "food" : "drink", "\n"
5192 }
5193
5194 age = {}
5195 age['Toddler'] = 3
5196 age['Unborn'] = 0
5197 age['Phantasm'] = nil
5198
5199 for thing in ['Toddler', 'Unborn', 'Phantasm', 'Relic']
5200 print "#{thing}: "
5201 print "Has-key " if age.has_key?(thing)
5202 print "True " if age[thing]
5203 print "Nonzero " if age[thing] && age[thing].nonzero?
5204 print "\n"
5205 end
5206
5207 #=>
5208 # Toddler: Has-key True Nonzero
5209 # Unborn: Has-key True
5210 # Phantasm: Has-key
5211 # Relic:
5212
5213 # You use Hash#has_key? when you use Perl's exists -> it checks
5214 # for existence of a key in a hash.
5215 # All Numeric are "True" in ruby, so the test doesn't have the
5216 # same semantics as in Perl; you would use Numeric#nonzero? to
5217 # achieve the same semantics (false if 0, true otherwise).
5218
5219
5220 # @@PLEAC@@_5.3
5221 food_color.delete("Banana")
5222
5223
5224 # @@PLEAC@@_5.4
5225 hash.each { |key, value|
5226 # do something with key and value
5227 }
5228
5229 hash.each_key { |key|
5230 # do something with key
5231 }
5232
5233 food_color.each { |food, color|
5234 puts "#{food} is #{color}"
5235 }
5236
5237 food_color.each_key { |food|
5238 puts "#{food} is #{food_color[food]}"
5239 }
5240
5241 # IMO this demonstrates that OO style is by far more readable
5242 food_color.keys.sort.each { |food|
5243 puts "#{food} is #{food_color[food]}."
5244 }
5245
5246 #-----------------------------
5247 #!/usr/bin/ruby
5248 # countfrom - count number of messages from each sender
5249
5250 # Default value is 0
5251 from = Hash.new(0)
5252 while gets
5253 /^From: (.*)/ and from[$1] += 1
5254 end
5255
5256 # More useful to sort by number of received mail by person
5257 from.sort {|a,b| b[1]<=>a[1]}.each { |v|
5258 puts "#{v[1]}: #{v[0]}"
5259 }
5260 #-----------------------------
5261
5262
5263 # @@PLEAC@@_5.5
5264 # You may use the built-in 'inspect' method this way:
5265 p hash
5266
5267 # Or do it the Cookbook way:
5268 hash.each { |k,v| puts "#{k} => #{v}" }
5269
5270 # Sorted by keys
5271 hash.sort.each { |e| puts "#{e[0]} => #{e[1]}" }
5272 # Sorted by values
5273 hash.sort{|a,b| a[1]<=>b[1]}.each { |e| puts "#{e[0]} => #{e[1]}" }
5274
5275
5276 # @@PLEAC@@_5.7
5277 ttys = Hash.new
5278 for i in `who`
5279 user, tty = i.split
5280 (ttys[user] ||= []) << tty # see problems_ruby for more infos
5281 end
5282 ttys.keys.sort.each { |k|
5283 puts "#{k}: #{commify_series(ttys[k])}" # from 4.2
5284 }
5285
5286
5287 # @@PLEAC@@_5.8
5288 surname = { "Mickey" => "Mantle", "Babe" => "Ruth" }
5289 puts surname.index("Mantle")
5290
5291 # If you really needed to 'invert' the whole hash, use Hash#invert
5292
5293 #-----------------------------
5294 #!/usr/bin/ruby -w
5295 # foodfind - find match for food or color
5296
5297 given = ARGV.shift or raise "usage: foodfind food_or_color"
5298
5299 color = {
5300 "Apple" => "red",
5301 "Banana" => "yellow",
5302 "Lemon" => "yellow",
5303 "Carrot" => "orange",
5304 }
5305
5306 if (color.has_key?(given))
5307 puts "#{given} is a food with color #{color[given]}."
5308 end
5309 if (color.has_value?(given))
5310 puts "#{color.index(given)} is a food with color #{given}."
5311 end
5312 #-----------------------------
5313
5314
5315 # @@PLEAC@@_5.9
5316 # Sorted by keys (Hash#sort gives an Array of pairs made of each key,value)
5317 food_color.sort.each { |f|
5318 puts "#{f[0]} is #{f[1]}."
5319 }
5320
5321 # Sorted by values
5322 food_color.sort { |a,b| a[1] <=> b[1] }.each { |f|
5323 puts "#{f[0]} is #{f[1]}."
5324 }
5325
5326 # Sorted by length of values
5327 food_color.sort { |a,b| a[1].length <=> b[1].length }.each { |f|
5328 puts "#{f[0]} is #{f[1]}."
5329 }
5330
5331
5332 # @@PLEAC@@_5.10
5333 merged = a.clone.update(b) # because Hash#update changes object in place
5334
5335 drink_color = { "Galliano" => "yellow", "Mai Tai" => "blue" }
5336 ingested_color = drink_color.clone.update(food_color)
5337
5338 substance_color = {}
5339 for i in [ food_color, drink_color ]
5340 i.each_key { |k|
5341 if substance_color.has_key?(k)
5342 puts "Warning: #{k} seen twice. Using the first definition."
5343 next
5344 end
5345 substance_color[k] = 1
5346 }
5347 end
5348
5349
5350 # @@PLEAC@@_5.11
5351 common = hash1.keys & hash2.keys
5352
5353 this_not_that = hash1.keys - hash2.keys
5354
5355
5356 # @@PLEAC@@_5.12
5357 # no problem here, Ruby handles any kind of object for key-ing
5358 # (it takes Object#hash, which defaults to Object#id)
5359
5360
5361 # @@PLEAC@@_5.13
5362 # AFAIK, not possible in Ruby
5363
5364
5365 # @@PLEAC@@_5.14
5366 # Be careful, the following is possible only because Fixnum objects are
5367 # special (documentation says: there is effectively only one Fixnum object
5368 # instance for any given integer value).
5369 count = Hash.new(0)
5370 array.each { |e|
5371 count[e] += 1
5372 }
5373
5374
5375 # @@PLEAC@@_5.15
5376 father = {
5377 "Cain" , "Adam",
5378 "Abel" , "Adam",
5379 "Seth" , "Adam",
5380 "Enoch" , "Cain",
5381 "Irad" , "Enoch",
5382 "Mehujael" , "Irad",
5383 "Methusael" , "Mehujael",
5384 "Lamech" , "Methusael",
5385 "Jabal" , "Lamech",
5386 "Jubal" , "Lamech",
5387 "Tubalcain" , "Lamech",
5388 "Enos" , "Seth",
5389 }
5390
5391 while gets
5392 chomp
5393 begin
5394 print $_, " "
5395 end while $_ = father[$_]
5396 puts
5397 end
5398
5399 children = {}
5400 father.each { |k,v|
5401 (children[v] ||= []) << k
5402 }
5403 while gets
5404 chomp
5405 puts "#{$_} begat #{(children[$_] || ['Nobody']).join(', ')}.\n"
5406 end
5407
5408 includes = {}
5409 files.each { |f|
5410 begin
5411 for l in IO.readlines(f)
5412 next unless l =~ /^\s*#\s*include\s*<([^>]+)>/
5413 (includes[$1] ||= []) << f
5414 end
5415 rescue SystemCallError
5416 $stderr.puts "#$! (skipping)"
5417 end
5418 }
5419
5420 include_free = includes.values.flatten.uniq - includes.keys
5421
5422
5423 # @@PLEAC@@_5.16
5424 # dutree - print sorted intented rendition of du output
5425 #% dutree
5426 #% dutree /usr
5427 #% dutree -a
5428 #% dutree -a /bin
5429
5430 # The DuNode class collects all information about a directory,
5431 # and provides some convenience methods
5432 class DuNode
5433
5434 attr_reader :name
5435 attr_accessor :size
5436 attr_accessor :kids
5437
5438 def initialize(name)
5439 @name = name
5440 @kids = []
5441 @size = 0
5442 end
5443
5444 # support for sorting nodes with side
5445 def size_compare(node2)
5446 @size <=> node2.size
5447 end
5448
5449 def basename
5450 @name.sub(/.*\//, "")
5451 end
5452
5453 #returns substring before last "/", nil if not there
5454 def parent
5455 p = @name.sub(/\/[^\/]+$/,"")
5456 if p == @name
5457 nil
5458 else
5459 p
5460 end
5461 end
5462
5463 end
5464
5465 # The DuTree does the acdtual work of
5466 # getting the input, parsing it, builging up a tree
5467 # and format it for output
5468 class Dutree
5469
5470 attr_reader :topdir
5471
5472 def initialize
5473 @nodes = Hash.new
5474 @dirsizes = Hash.new(0)
5475 @kids = Hash.new([])
5476 end
5477
5478 # get a node by name, create it if it does not exist yet
5479 def get_create_node(name)
5480 if @nodes.has_key?(name)
5481 @nodes[name]
5482 else
5483 node = DuNode.new(name)
5484 @nodes[name] = node
5485 node
5486 end
5487 end
5488
5489 # run du, read in input, save sizes and kids
5490 # stores last directory read in instance variable topdir
5491 def input(arguments)
5492 name = ""
5493 cmd = "du " + arguments.join(" ")
5494 IO.popen(cmd) { |pipe|
5495 pipe.each { |line|
5496 size, name = line.chomp.split(/\s+/, 2)
5497 node = get_create_node(name)
5498 node.size = size.to_i
5499 @nodes[name] = node
5500 parent = node.parent
5501 if parent
5502 get_create_node(parent).kids.push(node)
5503 end
5504 }
5505 }
5506 @topdir = @nodes[name]
5507 end
5508
5509 # figure out how much is taken in each directory
5510 # that isn't stored in the subdirectories. Add a new
5511 # fake kid called "." containing that much.
5512 def get_dots(node)
5513 cursize = node.size
5514 for kid in node.kids
5515 cursize -= kid.size
5516 get_dots(kid)
5517 end
5518 if node.size != cursize
5519 newnode = get_create_node(node.name + "/.")
5520 newnode.size = cursize
5521 node.kids.push(newnode)
5522 end
5523 end
5524
5525 # recursively output everything
5526 # passing padding and number width as well
5527 # on recursive calls
5528 def output(node, prefix="", width=0)
5529 line = sprintf("%#{width}d %s", node.size, node.basename)
5530 puts(prefix + line)
5531 prefix += line.sub(/\d /, "| ")
5532 prefix.gsub!(/[^|]/, " ")
5533 if node.kids.length > 0 # not a bachelor node
5534 kids = node.kids
5535 kids.sort! { |a,b|
5536 b.size_compare(a)
5537 }
5538 width = kids[0].size.to_s.length
5539 for kid in kids
5540 output(kid, prefix, width)
5541 end
5542 end
5543 end
5544
5545 end
5546
5547 tree = Dutree.new
5548 tree.input(ARGV)
5549 tree.get_dots(tree.topdir)
5550 tree.output(tree.topdir)
5551
5552
5553 # @@PLEAC@@_6.0
5554 # The verbose version are match, sub, gsub, sub! and gsub!;
5555 # pattern needs to be a Regexp object; it yields a MatchData
5556 # object.
5557 pattern.match(string)
5558 string.sub(pattern, replacement)
5559 string.gsub(pattern, replacement)
5560 # As usual in Ruby, sub! does the same as sub but also modifies
5561 # the object, the same for gsub!/gsub.
5562
5563 # Sugared syntax yields the position of the match (or nil if no
5564 # match). Note that the object at the right of the operator needs
5565 # not to be a Regexp object (it can be a String). The "dont
5566 # match" operator yields true or false.
5567 meadow =~ /sheep/ # position of the match, nil if no match
5568 meadow !~ /sheep/ # true if doesn't match, false if it does
5569 # There is no sugared version for the substitution
5570
5571 meadow =~ /\bovines?\b/i and print "Here be sheep!"
5572
5573 string = "good food"
5574 string.sub!(/o*/, 'e')
5575
5576 # % echo ababacaca | ruby -ne 'puts $& if /(a|ba|b)+(a|ac)+/'
5577 # ababa
5578
5579 # The "global" (or "multiple") match is handled by String#scan
5580 scan (/(\d+)/) {
5581 puts "Found number #{$1}"
5582 }
5583
5584 # String#scan yields an Array if not used with a block
5585 numbers = scan(/\d+/)
5586
5587 digits = "123456789"
5588 nonlap = digits.scan(/(\d\d\d)/)
5589 yeslap = digits.scan(/(?=(\d\d\d))/)
5590 puts "Non-overlapping: #{nonlap.join(' ')}"
5591 puts "Overlapping: #{yeslap.join(' ')}";
5592 # Non-overlapping: 123 456 789
5593 # Overlapping: 123 234 345 456 567 678 789
5594
5595 string = "And little lambs eat ivy"
5596 string =~ /l[^s]*s/
5597 puts "(#$`) (#$&) (#$')"
5598 # (And ) (little lambs) ( eat ivy)
5599
5600
5601 # @@PLEAC@@_6.1
5602 # Ruby doesn't have the same problem:
5603 dst = src.sub('this', 'that')
5604
5605 progname = $0.sub('^.*/', '')
5606
5607 bindirs = %w(/usr/bin /bin /usr/local/bin)
5608 libdirs = bindirs.map { |l| l.sub('bin', 'lib') }
5609
5610
5611 # @@PLEAC@@_6.3
5612 /\S+/ # as many non-whitespace bytes as possible
5613 /[A-Za-z'-]+/ # as many letters, apostrophes, and hyphens
5614
5615 /\b([A-Za-z]+)\b/ # usually best
5616 /\s([A-Za-z]+)\s/ # fails at ends or w/ punctuation
5617
5618
5619 # @@PLEAC@@_6.4
5620 require 'socket'
5621 str = 'www.ruby-lang.org and www.rubygarden.org'
5622 re = /
5623 ( # capture the hostname in $1
5624 (?: # these parens for grouping only
5625 (?! [-_] ) # lookahead for neither underscore nor dash
5626 [\w-] + # hostname component
5627 \. # and the domain dot
5628 ) + # now repeat that whole thing a bunch of times
5629 [A-Za-z] # next must be a letter
5630 [\w-] + # now trailing domain part
5631 ) # end of $1 capture
5632 /x # /x for nice formatting
5633
5634 str.gsub! re do # pass a block to execute replacement
5635 host = TCPsocket.gethostbyname($1)
5636 "#{$1} [#{host[3]}]"
5637 end
5638
5639 puts str
5640 #-----------------------------
5641 # to match whitespace or #-characters in an extended re you need to escape
5642 # them.
5643
5644 foo = 42
5645 str = 'blah #foo# blah'
5646 str.gsub! %r/ # replace
5647 \# # a pound sign
5648 (\w+) # the variable name
5649 \# # another pound sign
5650 /x do
5651 eval $1 # with the value of a local variable
5652 end
5653 puts str # => blah 42 blah
5654
5655
5656 # @@PLEAC@@_6.5
5657 # The 'g' modifier doesn't exist in Ruby, a regexp can't be used
5658 # directly in a while loop; instead, use String#scan { |match| .. }
5659 fish = 'One fish two fish red fish blue fish'
5660 WANT = 3
5661 count = 0
5662 fish.scan(/(\w+)\s+fish\b/i) {
5663 if (count += 1) == WANT
5664 puts "The third fish is a #{$1} one."
5665 end
5666 }
5667
5668 if fish =~ /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i
5669 puts "The third fish is a #{$1} one."
5670 end
5671
5672 pond = 'One fish two fish red fish blue fish'
5673 # String#scan without a block gives an array of matches, each match
5674 # being an array of all the specified groups
5675 colors = pond.scan(/(\w+)\s+fish\b/i).flatten # get all matches
5676 color = colors[2] # then the one we want
5677 # or without a temporary array
5678 color = pond.scan(/(\w+)\s+fish\b/i).flatten[2] # just grab element 3
5679 puts "The third fish in the pond is #{color}."
5680
5681 count = 0
5682 fishes = 'One fish two fish red fish blue fish'
5683 evens = fishes.scan(/(\w+)\s+fish\b/i).select { (count+=1) % 2 == 0 }
5684 print "Even numbered fish are #{evens.join(' ')}."
5685
5686 count = 0
5687 fishes.gsub(/
5688 \b # makes next \w more efficient
5689 ( \w+ ) # this is what we\'ll be changing
5690 (
5691 \s+ fish \b
5692 )
5693 /x) {
5694 if (count += 1) == 4
5695 'sushi' + $2
5696 else
5697 $1 + $2
5698 end
5699 }
5700
5701 pond = 'One fish two fish red fish blue fish swim here.'
5702 puts "Last fish is #{pond.scan(/\b(\w+)\s+fish\b/i).flatten[-1]}"
5703
5704 /
5705 A # find some pattern A
5706 (?! # mustn\'t be able to find
5707 .* # something
5708 A # and A
5709 )
5710 $ # through the end of the string
5711 /x
5712
5713 # The "s" perl modifier is "m" in Ruby (not very nice since there is
5714 # also an "m" in perl..)
5715 pond = "One fish two fish red fish blue fish swim here."
5716 if (pond =~ /
5717 \b ( \w+) \s+ fish \b
5718 (?! .* \b fish \b )
5719 /mix)
5720 puts "Last fish is #{$1}."
5721 else
5722 puts "Failed!"
5723 end
5724
5725
5726 # @@PLEAC@@_6.6
5727 #-----------------------------
5728 #!/usr/bin/ruby -w
5729 # killtags - very bad html killer
5730 $/ = nil; # each read is whole file
5731 while file = gets() do
5732 file.gsub!(/<.*?>/m,''); # strip tags (terribly)
5733 puts file # print file to STDOUT
5734 end
5735 #-----------------------------
5736 #!/usr/bin/ruby -w
5737 #headerfy - change certain chapter headers to html
5738 $/ = ''
5739 while file = gets() do
5740 pattern = /
5741 \A # start of record
5742 ( # capture in $1
5743 Chapter # text string
5744 \s+ # mandatory whitespace
5745 \d+ # decimal number
5746 \s* # optional whitespace
5747 : # a real colon
5748 . * # anything not a newline till end of line
5749 )
5750 /x
5751 puts file.gsub(pattern,'<H1>\1</H1>')
5752 end
5753 #-----------------------------
5754 #% ruby -00pe "gsub!(/\A(Chapter\s+\d+\s*:.*)/,'<H1>\1</H1>')" datafile
5755
5756 #!/usr/bin/ruby -w
5757 #-----------------------------
5758 for file in ARGV
5759 file = File.open(ARGV.shift)
5760 while file.gets('') do # each read is a paragraph
5761 print "chunk #{$.} in $ARGV has <<#{$1}>>\n" while /^START(.*?)^END/m
5762 end # /m activates the multiline mode
5763 end
5764 #-----------------------------
5765
5766 # @@PLEAC@@_6.7
5767 #-----------------------------
5768 $/ = nil;
5769 file = File.open("datafile")
5770 chunks = file.gets.split(/pattern/)
5771 #-----------------------------
5772 # .Ch, .Se and .Ss divide chunks of STDIN
5773 chunks = gets(nil).split(/^\.(Ch|Se|Ss)$/)
5774 print "I read #{chunks.size} chunks.\n"
5775 #-----------------------------
5776
5777
5778 # @@PLEAC@@_6.8
5779 while gets
5780 if ~/BEGIN/ .. ~/END/
5781 # line falls between BEGIN and END inclusive
5782 end
5783 end
5784
5785 while gets
5786 if ($. == firstnum) .. ($. == lastnum)
5787 # operate between firstnum and lastnum line number
5788 end
5789 end
5790
5791 # in ruby versions prior to 1.8, the above two conditional
5792 # expressions could be shortened to:
5793 # if /BEGIN/ .. /END/
5794 # and
5795 # if firstnum .. lastnum
5796 # but these now only work this way from the command line
5797
5798 #-----------------------------
5799
5800 while gets
5801 if ~/BEGIN/ ... ~/END/
5802 # line falls between BEGIN and END on different lines
5803 end
5804 end
5805
5806 while gets
5807 if ($. == first) ... ($. == last)
5808 # operate between first and last line number on different lines
5809 end
5810 end
5811
5812 #-----------------------------
5813 # command-line to print lines 15 through 17 inclusive (see below)
5814 ruby -ne 'print if 15 .. 17' datafile
5815
5816 # print out all <XMP> .. </XMP> displays from HTML doc
5817 while gets
5818 print if ~%r#<XMP>#i .. ~%r#</XMP>#i;
5819 end
5820
5821 # same, but as shell command
5822 # ruby -ne 'print if %r#<XMP>#i .. %r#</XMP>#i' document.html
5823 #-----------------------------
5824 # ruby -ne 'BEGIN { $top=3; $bottom=5 }; \
5825 # print if $top .. $bottom' /etc/passwd # FAILS
5826 # ruby -ne 'BEGIN { $top=3; $bottom=5 }; \
5827 # print if $. == $top .. $. == $bottom' /etc/passwd # works
5828 # ruby -ne 'print if 3 .. 5' /etc/passwd # also works
5829 #-----------------------------
5830 print if ~/begin/ .. ~/end/;
5831 print if ~/begin/ ... ~/end/;
5832 #-----------------------------
5833 while gets
5834 $in_header = $. == 1 .. ~/^$/ ? true : false
5835 $in_body = ~/^$/ .. ARGF.eof ? true : false
5836 end
5837 #-----------------------------
5838 seen = {}
5839 ARGF.each do |line|
5840 next unless line =~ /^From:?\s/i .. line =~ /^$/;
5841 line.scan(%r/([^<>(),;\s]+\@[^<>(),;\s]+)/).each do |addr|
5842 puts addr unless seen[addr]
5843 seen[addr] ||= 1
5844 end
5845 end
5846
5847
5848 # @@PLEAC@@_6.9
5849 def glob2pat(globstr)
5850 patmap = {
5851 '*' => '.*',
5852 '?' => '.',
5853 '[' => '[',
5854 ']' => ']',
5855 }
5856 globstr.gsub!(/(.)/) { |c| patmap[c] || Regexp::escape(c) }
5857 '^' + globstr + '$'
5858 end
5859
5860
5861 # @@PLEAC@@_6.10
5862 # avoid interpolating patterns like this if the pattern
5863 # isn't going to change:
5864 pattern = ARGV.shift
5865 ARGF.each do |line|
5866 print line if line =~ /#{pattern}/
5867 end
5868
5869 # the above creates a new regex each iteration. Instead,
5870 # use the /o modifier so the regex is compiled only once
5871
5872 pattern = ARGV.shift
5873 ARGF.each do |line|
5874 print line if line =~ /#{pattern}/o
5875 end
5876
5877 #-----------------------------
5878
5879 #!/usr/bin/ruby
5880 # popgrep1 - grep for abbreviations of places that say "pop"
5881 # version 1: slow but obvious way
5882 popstates = %w(CO ON MI WI MN)
5883 ARGF.each do |line|
5884 popstates.each do |state|
5885 if line =~ /\b#{state}\b/
5886 print line
5887 last
5888 end
5889 end
5890 end
5891
5892 #-----------------------------
5893 #!/usr/bin/ruby
5894 # popgrep2 - grep for abbreviations of places that say "pop"
5895 # version 2: eval strings; fast but hard to quote
5896 popstates = %w(CO ON MI WI MN)
5897 code = "ARGF.each do |line|\n"
5898 popstates.each do |state|
5899 code += "\tif line =~ /\\b#{state}\\b/; print(line); next; end\n"
5900 end
5901 code += "end\n"
5902 print "CODE IS\n---\n#{code}\n---\n" if false # turn on for debugging
5903 eval code
5904
5905 # CODE IS
5906 # ---
5907 # ARGF.each do |line|
5908 # if line =~ /\bCO\b/; print(line); next; end
5909 # if line =~ /\bON\b/; print(line); next; end
5910 # if line =~ /\bMI\b/; print(line); next; end
5911 # if line =~ /\bWI\b/; print(line); next; end
5912 # if line =~ /\bMN\b/; print(line); next; end
5913 # end
5914 #
5915 # ---
5916
5917 ## alternatively, the same idea as above but compiling
5918 ## to a case statement: (not in perlcookbook)
5919 #!/usr/bin/ruby -w
5920 # popgrep2.5 - grep for abbreviations of places that say "pop"
5921 # version 2.5: eval strings; fast but hard to quote
5922 popstates = %w(CO ON MI WI MN)
5923 code = "ARGF.each do |line|\n case line\n"
5924 popstates.each do |state|
5925 code += " when /\\b#{state}\\b/ : print line\n"
5926 end
5927 code += " end\nend\n"
5928 print "CODE IS\n---\n#{code}\n---\n" if false # turn on for debugging
5929 eval code
5930
5931 # CODE IS
5932 # ---
5933 # ARGF.each do |line|
5934 # case line
5935 # when /\bCO\b/ : print line
5936 # when /\bON\b/ : print line
5937 # when /\bMI\b/ : print line
5938 # when /\bWI\b/ : print line
5939 # when /\bMN\b/ : print line
5940 # end
5941 # end
5942 #
5943 # ---
5944
5945 # Note: (above) Ruby 1.8+ allows the 'when EXP : EXPR' on one line
5946 # with the colon separator.
5947
5948 #-----------------------------
5949 #!/usr/bin/ruby
5950 # popgrep3 - grep for abbreviations of places that say "pop"
5951 # version3: build a match_any function
5952 popstates = %w(CO ON MI WI MN)
5953 expr = popstates.map{|e|"line =~ /\\b#{e}\\b/"}.join('||')
5954 eval "def match_any(line); #{expr};end"
5955 ARGF.each do |line|
5956 print line if match_any(line)
5957 end
5958 #-----------------------------
5959
5960 ## building a match_all function is a trivial
5961 ## substitution of && for ||
5962 ## here is a generalized example:
5963 #!/usr/bin/ruby -w
5964 ## grepauth - print lines that mention both foo and bar
5965 class MultiMatch
5966 def initialize(*patterns)
5967 _any = build_match('||',patterns)
5968 _all = build_match('&&',patterns)
5969 eval "def match_any(line);#{_any};end\n"
5970 eval "def match_all(line);#{_all};end\n"
5971 end
5972 def build_match(sym,args)
5973 args.map{|e|"line =~ /#{e}/"}.join(sym)
5974 end
5975 end
5976
5977 mm = MultiMatch.new('foo','bar')
5978 ARGF.each do |line|
5979 print line if mm.match_all(line)
5980 end
5981 #-----------------------------
5982
5983 #!/usr/bin/ruby
5984 # popgrep4 - grep for abbreviations of places that say "pop"
5985 # version4: pretty fast, but simple: compile all re's first:
5986 popstates = %w(CO ON MI WI MN)
5987 popstates = popstates.map{|re| %r/\b#{re}\b/}
5988 ARGF.each do |line|
5989 popstates.each do |state_re|
5990 if line =~ state_re
5991 print line
5992 break
5993 end
5994 end
5995 end
5996
5997 ## speeds trials on the jargon file(412): 26006 lines, 1.3MB
5998 ## popgrep1 => 7.040s
5999 ## popgrep2 => 0.656s
6000 ## popgrep2.5 => 0.633s
6001 ## popgrep3 => 0.675s
6002 ## popgrep4 => 1.027s
6003
6004 # unless speed is criticial, the technique in popgrep4 is a
6005 # reasonable balance between speed and logical simplicity.
6006
6007
6008 # @@PLEAC@@_6.11
6009 begin
6010 print "Pattern? "
6011 pat = $stdin.gets.chomp
6012 Regexp.new(pat)
6013 rescue
6014 warn "Invalid Pattern"
6015 retry
6016 end
6017
6018
6019 # @@PLEAC@@_6.13
6020 # uses the 'amatch' extension found on:
6021 # http://raa.ruby-lang.org/project/amatch/
6022 require 'amatch'
6023 matcher = Amatch.new('balast')
6024 #$relative, $distance = 0, 1
6025 File.open('/usr/share/dict/words').each_line do |line|
6026 print line if matcher.search(line) <= 1
6027 end
6028 #__END__
6029 #CODE
6030 ballast
6031 ballasts
6032 balustrade
6033 balustrades
6034 blast
6035 blasted
6036 blaster
6037 blasters
6038 blasting
6039 blasts
6040
6041
6042 # @@PLEAC@@_6.14
6043 str.scan(/\G(\d)/).each do |token|
6044 puts "found #{token}"
6045 end
6046 #-----------------------------
6047 n = " 49 here"
6048 n.gsub!(/\G /,'0')
6049 puts n
6050 #-----------------------------
6051 str = "3,4,5,9,120"
6052 str.scan(/\G,?(\d+)/).each do |num|
6053 puts "Found number: #{num}"
6054 end
6055 #-----------------------------
6056 # Ruby doesn't have the String.pos or a /c re modifier like Perl
6057 # But it does have StringScanner in the standard library (strscn)
6058 # which allows similar functionality:
6059
6060 require 'strscan'
6061 text = 'the year 1752 lost 10 days on the 3rd of September'
6062 sc = StringScanner.new(text)
6063 while sc.scan(/.*?(\d+)/)
6064 print "found: #{sc[1]}\n"
6065 end
6066 if sc.scan(/\S+/)
6067 puts "Found #{sc[0]} after last number"
6068 end
6069 #-----------------------------
6070 # assuming continuing from above:
6071 puts "The position in 'text' is: #{sc.pos}"
6072 sc.pos = 30
6073 puts "The position in 'text' is: #{sc.pos}"
6074
6075
6076 # @@PLEAC@@_6.15
6077 #-----------------------------
6078 # greedy pattern
6079 str.gsub!(/<.*>/m,'') # not good
6080
6081 # non-greedy (minimal) pattern
6082 str.gsub!(/<.*?>/m,'') # not great
6083
6084
6085 #-----------------------------
6086 #<b><i>this</i> and <i>that</i> are important</b> Oh, <b><i>me too!</i></b>
6087 #-----------------------------
6088 %r{ <b><i>(.*?)</i></b> }mx
6089 #-----------------------------
6090 %r/BEGIN((?:(?!BEGIN).)*)END/
6091 #-----------------------------
6092 %r{ <b><i>( (?: (?!</b>|</i>). )* ) </i></b> }mx
6093 #-----------------------------
6094 %r{ <b><i>( (?: (?!</[ib]>). )* ) </i></b> }mx
6095 #-----------------------------
6096 %r{
6097 <b><i>
6098 [^<]* # stuff not possibly bad, and not possibly the end.
6099 (?:
6100 # at this point, we can have '<' if not part of something bad
6101 (?! </?[ib]> ) # what we can't have
6102 < # okay, so match the '<'
6103 [^<]* # and continue with more safe stuff
6104 ) *
6105 </i></b>
6106 }mx
6107
6108
6109 # @@PLEAC@@_6.16
6110 #-----------------------------
6111 $/ = ""
6112 ARGF.each do |para|
6113 para.scan %r/
6114 \b # start at word boundary
6115 (\S+) # find chunk of non-whitespace
6116 \b # until a word boundary
6117 (
6118 \s+ # followed by whitespace
6119 \1 # and that same chunk again
6120 \b # and a word boundary
6121 ) + # one or more times
6122 /xi do
6123 puts "dup word '#{$1}' at paragraph #{$.}"
6124 end
6125 end
6126 #-----------------------------
6127 astr = 'nobody'
6128 bstr = 'bodysnatcher'
6129 if "#{astr} #{bstr}" =~ /^(\w+)(\w+) \2(\w+)$/
6130 print "#{$2} overlaps in #{$1}-#{$2}-#{$3}"
6131 end
6132 #-----------------------------
6133 #!/usr/bin/ruby -w
6134 # prime_pattern -- find prime factors of argument using patterns
6135 ARGV << 180
6136 cap = 'o' * ARGV.shift
6137 while cap =~ /^(oo+?)\1+$/
6138 print $1.size, " "
6139 cap.gsub!(/#{$1}/,'o')
6140 end
6141 puts cap.size
6142 #-----------------------------
6143 #diophantine
6144 # solve for 12x + 15y + 16z = 281, maximizing x
6145 if ('o' * 281).match(/^(o*)\1{11}(o*)\2{14}(o*)\3{15}$/)
6146 x, y, z = $1.size, $2.size, $3.size
6147 puts "One solution is: x=#{x}; y=#{y}; z=#{z}"
6148 else
6149 puts "No solution."
6150 end
6151 # => One solution is: x=17; y=3; z=2
6152
6153 #-----------------------------
6154 # using different quantifiers:
6155 ('o' * 281).match(/^(o+)\1{11}(o+)\2{14}(o+)\3{15}$/)
6156 # => One solution is: x=17; y=3; z=2
6157
6158 ('o' * 281).match(/^(o*?)\1{11}(o*)\2{14}(o*)\3{15}$/)
6159 # => One solution is: x=0; y=7; z=11
6160
6161 ('o' * 281).match(/^(o+?)\1{11}(o*)\2{14}(o*)\3{15}$/)
6162 # => One solution is: x=1; y=3; z=14
6163
6164
6165 # @@PLEAC@@_6.17
6166 # alpha OR beta
6167 %r/alpha|beta/
6168
6169 # alpha AND beta
6170 %r/(?=.*alpha)(?=.*beta)/m
6171
6172 # alpha AND beta, no overlap
6173 %r/alpha.*beta|beta.*alpha/m
6174
6175 # NOT beta
6176 %r/^(?:(?!beta).)*$/m
6177
6178 # NOT bad BUT good
6179 %r/(?=(?:(?!BAD).)*$)GOOD/m
6180 #-----------------------------
6181
6182 if !(string =~ /pattern/) # ugly
6183 something()
6184 end
6185
6186 if string !~ /pattern/ # preferred
6187 something()
6188 end
6189
6190
6191 #-----------------------------
6192 if string =~ /pat1/ && string =~ /pat2/
6193 something()
6194 end
6195 #-----------------------------
6196 if string =~ /pat1/ || string =~ /pat2/
6197 something()
6198 end
6199 #-----------------------------
6200 #!/usr/bin/ruby -w
6201 # minigrep - trivial grep
6202 pat = ARGV.shift
6203 ARGF.each do |line|
6204 print line if line =~ /#{pat}/o
6205 end
6206 #-----------------------------
6207 "labelled" =~ /^(?=.*bell)(?=.*lab)/m
6208 #-----------------------------
6209 $string =~ /bell/ && $string =~ /lab/
6210 #-----------------------------
6211 $murray_hill = "blah bell blah "
6212 if $murray_hill =~ %r{
6213 ^ # start of string
6214 (?= # zero-width lookahead
6215 .* # any amount of intervening stuff
6216 bell # the desired bell string
6217 ) # rewind, since we were only looking
6218 (?= # and do the same thing
6219 .* # any amount of intervening stuff
6220 lab # and the lab part
6221 )
6222 }mx # /m means . can match newline
6223
6224 print "Looks like Bell Labs might be in Murray Hill!\n";
6225 end
6226 #-----------------------------
6227 "labelled" =~ /(?:^.*bell.*lab)|(?:^.*lab.*bell)/
6228 #-----------------------------
6229 $brand = "labelled";
6230 if $brand =~ %r{
6231 (?: # non-capturing grouper
6232 ^ .*? # any amount of stuff at the front
6233 bell # look for a bell
6234 .*? # followed by any amount of anything
6235 lab # look for a lab
6236 ) # end grouper
6237 | # otherwise, try the other direction
6238 (?: # non-capturing grouper
6239 ^ .*? # any amount of stuff at the front
6240 lab # look for a lab
6241 .*? # followed by any amount of anything
6242 bell # followed by a bell
6243 ) # end grouper
6244 }mx # /m means . can match newline
6245 print "Our brand has bell and lab separate.\n";
6246 end
6247 #-----------------------------
6248 $map =~ /^(?:(?!waldo).)*$/s
6249 #-----------------------------
6250 $map = "the great baldo"
6251 if $map =~ %r{
6252 ^ # start of string
6253 (?: # non-capturing grouper
6254 (?! # look ahead negation
6255 waldo # is he ahead of us now?
6256 ) # is so, the negation failed
6257 . # any character (cuzza /s)
6258 ) * # repeat that grouping 0 or more
6259 $ # through the end of the string
6260 }mx # /m means . can match newline
6261 print "There's no waldo here!\n";
6262 end
6263 =begin
6264 7:15am up 206 days, 13:30, 4 users, load average: 1.04, 1.07, 1.04
6265
6266 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
6267
6268 tchrist tty1 5:16pm 36days 24:43 0.03s xinit
6269
6270 tchrist tty2 5:19pm 6days 0.43s 0.43s -tcsh
6271
6272 tchrist ttyp0 chthon 7:58am 3days 23.44s 0.44s -tcsh
6273
6274 gnat ttyS4 coprolith 2:01pm 13:36m 0.30s 0.30s -tcsh
6275 =end
6276 #% w | minigrep '^(?!.*ttyp).*tchrist'
6277 #-----------------------------
6278 %r{
6279 ^ # anchored to the start
6280 (?! # zero-width look-ahead assertion
6281 .* # any amount of anything (faster than .*?)
6282 ttyp # the string you don't want to find
6283 ) # end look-ahead negation; rewind to start
6284 .* # any amount of anything (faster than .*?)
6285 tchrist # now try to find Tom
6286 }x
6287 #-----------------------------
6288 #% w | grep tchrist | grep -v ttyp
6289 #-----------------------------
6290 #% grep -i 'pattern' files
6291 #% minigrep '(?i)pattern' files
6292 #-----------------------------
6293
6294
6295 # @@PLEAC@@_6.20
6296 ans = $stdin.gets.chomp
6297 re = %r/^#{Regexp.quote(ans)}/
6298 case
6299 when "SEND" =~ re : puts "Action is send"
6300 when "STOP" =~ re : puts "Action is stop"
6301 when "ABORT" =~ re : puts "Action is abort"
6302 when "EDIT" =~ re : puts "Action is edit"
6303 end
6304 #-----------------------------
6305 require 'abbrev'
6306 table = Abbrev.abbrev %w-send stop abort edit-
6307 loop do
6308 print "Action: "
6309 ans = $stdin.gets.chomp
6310 puts "Action for #{ans} is #{table[ans.downcase]}"
6311 end
6312
6313
6314 #-----------------------------
6315 # dummy values are defined for 'file', 'PAGER', and
6316 # the 'invoke_editor' and 'deliver_message' methods
6317 # do not do anything interesting in this example.
6318 #!/usr/bin/ruby -w
6319 require 'abbrev'
6320
6321 file = 'pleac_ruby.data'
6322 PAGER = 'less'
6323
6324 def invoke_editor
6325 puts "invoking editor"
6326 end
6327
6328 def deliver_message
6329 puts "delivering message"
6330 end
6331
6332 actions = {
6333 'edit' => self.method(:invoke_editor),
6334 'send' => self.method(:deliver_message),
6335 'list' => proc {system(PAGER, file)},
6336 'abort' => proc {puts "See ya!"; exit},
6337 "" => proc {puts "Unknown Command"}
6338 }
6339
6340 dtable = Abbrev.abbrev(actions.keys)
6341 loop do
6342 print "Action: "
6343 ans = $stdin.gets.chomp.delete(" \t")
6344 actions[ dtable[ans.downcase] || "" ].call
6345 end
6346
6347
6348 # @@PLEAC@@_6.19
6349 #-----------------------------
6350 # basically, the Perl Cookbook categorizes this as an
6351 # unsolvable problem ...
6352 #-----------------------------
6353 1 while addr.gsub!(/\([^()]*\)/,'')
6354 #-----------------------------
6355 Dear [email protected],
6356
6357 Please confirm the mail address you gave us Wed May 6 09:38:41
6358 MDT 1998 by replying to this message. Include the string
6359 "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
6360 start with "Nik...". Once this is done, your confirmed address will
6361 be entered into our records.
6362
6363
6364 # @@PLEAC@@_6.21
6365 #-----------------------------
6366 #% gunzip -c ~/mail/archive.gz | urlify > archive.urlified
6367 #-----------------------------
6368 #% urlify ~/mail/*.inbox > ~/allmail.urlified
6369 #-----------------------------
6370 #!/usr/bin/ruby -w
6371 # urlify - wrap HTML links around URL-like constructs
6372
6373 urls = '(https?|telnet|gopher|file|wais|ftp)';
6374 ltrs = '\w';
6375 gunk = '/#~:.?+=&%@!\-';
6376 punc = '.:?\-';
6377 any = "#{ltrs}#{gunk}#{punc}";
6378
6379 ARGF.each do |line|
6380 line.gsub! %r/
6381 \b # start at word boundary
6382 ( # begin $1 {
6383 #{urls} : # need resource and a colon
6384 [#{any}] +? # followed by on or more
6385 # of any valid character, but
6386 # be conservative and take only
6387 # what you need to....
6388 ) # end $1 }
6389 (?= # look-ahead non-consumptive assertion
6390 [#{punc}]* # either 0 or more punctuation
6391 [^#{any}] # followed by a non-url char
6392 | # or else
6393 $ # then end of the string
6394 )
6395 /iox do
6396 %Q|<A HREF="#{$1}">#{$1}</A>|
6397 end
6398 print line
6399 end
6400
6401
6402 # @@PLEAC@@_6.23
6403 %r/^m*(d?c{0,3}|c[dm])(l?x{0,3}|x[lc])(v?i{0,3}|i[vx])$/i
6404 #-----------------------------
6405 str.sub!(/(\S+)(\s+)(\S+)/, '\3\2\1')
6406 #-----------------------------
6407 %r/(\w+)\s*=\s*(.*)\s*$/ # keyword is $1, value is $2
6408 #-----------------------------
6409 %r/.{80,}/
6410 #-----------------------------
6411 %r|(\d+)/(\d+)/(\d+) (\d+):(\d+):(\d+)|
6412 #-----------------------------
6413 str.gsub!(%r|/usr/bin|,'/usr/local/bin')
6414 #-----------------------------
6415 str.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/){ $1.hex.chr }
6416 #-----------------------------
6417 str.gsub!(%r{
6418 /\* # Match the opening delimiter
6419 .*? # Match a minimal number of characters
6420 \*/ # Match the closing delimiter
6421 }xm,'')
6422 #-----------------------------
6423 str.sub!(/^\s+/, '')
6424 str.sub!(/\s+$/, '')
6425
6426 # but really, in Ruby we'd just do:
6427 str.strip!
6428 #-----------------------------
6429 str.gsub!(/\\n/,"\n")
6430 #-----------------------------
6431 str.sub!(/^.*::/, '')
6432 #-----------------------------
6433 %r/^([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])\.
6434 ([01]?\d\d|2[0-4]\d|25[0-5])\.([01]?\d\d|2[0-4]\d|25[0-5])$/x
6435 #-----------------------------
6436 str.sub!(%r|^.*/|, '')
6437 #-----------------------------
6438 cols = ( (ENV['TERMCAP'] || " ") =~ /:co#(\d+):/ ) ? $1 : 80;
6439 #-----------------------------
6440 name = " #{$0} #{ARGV}".gsub(%r| /\S+/|, ' ')
6441 #-----------------------------
6442 require 'rbconfig'
6443 include Config
6444 raise "This isn't Linux" unless CONFIG['target_os'] =~ /linux/i;
6445 #-----------------------------
6446 str.gsub!(%r/\n\s+/, ' ')
6447 #-----------------------------
6448 nums = str.scan(/(\d+\.?\d*|\.\d+)/)
6449 #-----------------------------
6450 capwords = str.scan(%r/(\b[^\Wa-z0-9_]+\b)/)
6451 #-----------------------------
6452 lowords = str.scan(%r/(\b[^\WA-Z0-9_]+\b)/)
6453 #-----------------------------
6454 icwords = str.scan(%r/(\b[^\Wa-z0-9_][^\WA-Z0-9_]*\b)/)
6455 #-----------------------------
6456 links = str.scan(%r/<A[^>]+?HREF\s*=\s*["']?([^'" >]+?)[ '"]?>/mi)
6457 #-----------------------------
6458 initial = str =~ /^\S+\s+(\S)\S*\s+\S/ ? $1 : ""
6459 #-----------------------------
6460 str.gsub!(%r/"([^"]*)"/, %q-``\1''-)
6461 #-----------------------------
6462
6463 $/ = ""
6464 sentences = []
6465 ARGF.each do |para|
6466 para.gsub!(/\n/, ' ')
6467 para.gsub!(/ {3,}/,' ')
6468 sentences << para.scan(/(\S.*?[!?.])(?= |\Z)/)
6469 end
6470
6471 #-----------------------------
6472 %r/(\d{4})-(\d\d)-(\d\d)/ # YYYY in $1, MM in $2, DD in $3
6473 #-----------------------------
6474 %r/ ^
6475 (?:
6476 1 \s (?: \d\d\d \s)? # 1, or 1 and area code
6477 | # ... or ...
6478 \(\d\d\d\) \s # area code with parens
6479 | # ... or ...
6480 (?: \+\d\d?\d? \s)? # optional +country code
6481 \d\d\d ([\s\-]) # and area code
6482 )
6483 \d\d\d (\s|\1) # prefix (and area code separator)
6484 \d\d\d\d # exchange
6485 $
6486 /x
6487 #-----------------------------
6488 %r/\boh\s+my\s+gh?o(d(dess(es)?|s?)|odness|sh)\b/i
6489 #-----------------------------
6490 lines = []
6491 lines << $1 while input.sub!(/^([^\012\015]*)(\012\015?|\015\012?)/,'')
6492
6493
6494 # @@PLEAC@@_7.0
6495 # An IO object being Enumerable, we can use 'each' directly on it
6496 File.open("/usr/local/widgets/data").each { |line|
6497 puts line if line =~ /blue/
6498 }
6499
6500 logfile = File.new("/var/log/rubylog.txt", "w")
6501 mysub($stdin, logfile)
6502
6503 # The method IO#readline is similar to IO#gets
6504 # but throws an exception when it reaches EOF
6505 f = File.new("bla.txt")
6506 begin
6507 while (line = f.readline)
6508 line.chomp
6509 $stdout.print line if line =~ /blue/
6510 end
6511 rescue EOFError
6512 f.close
6513 end
6514
6515 while $stdin.gets # reads from STDIN
6516 unless (/\d/)
6517 $stderr.puts "No digit found." # writes to STDERR
6518 end
6519 puts "Read: #{$_}" # writes to STDOUT
6520 end
6521
6522 logfile = File.new("/tmp/log", "w")
6523
6524 logfile.close
6525
6526 # $defout (or its synonym '$>') is the destination of output
6527 # for Kernel#print, Kernel#puts, and family functions
6528 logfile = File.new("log.txt", "w")
6529 old = $defout
6530 $defout = logfile # switch to logfile for output
6531 puts "Countdown initiated ..."
6532 $defout = old # return to original output
6533 puts "You have 30 seconds to reach minimum safety distance."
6534
6535
6536 # @@PLEAC@@_7.1
6537 source = File.new(path, "r") # open file "path" for reading only
6538 sink = File.new(path, "w") # open file "path" for writing only
6539
6540 source = File.open(path, File::RDONLY) # open file "path" for reading only
6541 sink = File.open(path, File::WRONLY) # open file "path" for writing only
6542
6543 file = File.open(path, "r+") # open "path" for reading and writing
6544 file = File.open(path, flags) # open "path" with the flags "flags" (see examples below for flags)
6545
6546 # open file "path" read only
6547 file = File.open(path, "r")
6548 file = File.open(path, File::RDONLY)
6549
6550 # open file "path" write only, create it if it does not exist
6551 # truncate it to zero length if it exists
6552 file = File.open(path, "w")
6553 file = File.open(path, File::WRONLY|File::TRUNC|File::CREAT)
6554 file = File.open(path, File::WRONLY|File::TRUNC|File::CREAT, 0666) # with permission 0666
6555
6556 # open file "path" write only, fails if file exists
6557 file = File.open(path, File::WRONLY|File::EXCL|File::CREAT)
6558 file = File.open(path, File::WRONLY|File::EXCL|File::CREAT, 0666)
6559
6560 # open file "path" for appending
6561 file = File.open(path, "a")
6562 file = File.open(path, File::WRONLY|File::APPEND|File::CREAT)
6563 file = File.open(path, File::WRONLY|File::APPEND|File::CREAT, 0666)
6564
6565 # open file "path" for appending only when file exists
6566 file = File.open(path, File::WRONLY|File::APPEND)
6567
6568 # open file "path" for reading and writing
6569 file = File.open(path, "r+")
6570 file = File.open(path, File::RDWR)
6571
6572 # open file for reading and writing, create a new file if it does not exist
6573 file = File.open(path, File::RDWR|File::CREAT)
6574 file = File.open(path, File::RDWR|File::CREAT, 0600)
6575
6576 # open file "path" reading and writing, fails if file exists
6577 file = File.open(path, File::RDWR|File::EXCL|File::CREAT)
6578 file = File.open(path, File::RDWR|File::EXCL|File::CREAT, 0600)
6579
6580
6581 # @@PLEAC@@_7.2
6582 # No problem with Ruby since the filename doesn't contain characters with
6583 # special meaning; like Perl's sysopen
6584 File.open(filename, 'r')
6585
6586
6587 # @@PLEAC@@_7.3
6588 File.expand_path('~root/tmp')
6589 #=> "/root/tmp"
6590 File.expand_path('~rpcuser')
6591 #=> "/var/lib/nfs"
6592
6593 # To expand ~/.. it explicitely needs the environment variable HOME
6594 File.expand_path('~/tmp')
6595 #=> "/home/gc/tmp"
6596
6597
6598 # @@PLEAC@@_7.4
6599 # The exception raised in Ruby reports the filename
6600 File.open('afile')
6601
6602
6603 # @@PLEAC@@_7.5
6604 # Standard Ruby distribution provides the following useful extension
6605 require 'tempfile'
6606 # With the Tempfile class, the file is automatically deleted on garbage
6607 # collection, so you won't need to remove it, later on.
6608 tf = Tempfile.new('tmp') # a name is required to create the filename
6609
6610 # If you need to pass the filename to an external program you can use
6611 # File#path, but don't forget to File#flush in order to flush anything
6612 # living in some buffer somewhere.
6613 tf.flush
6614 system("/usr/bin/dowhatever #{tf.path}")
6615
6616 fh = Tempfile.new('tmp')
6617 fh.sync = true # autoflushes
6618 10.times { |i| fh.puts i }
6619 fh.rewind
6620 puts 'Tmp file has: ', fh.readlines
6621
6622
6623 # @@PLEAC@@_7.6
6624 while (DATA.gets) do
6625 # process the line
6626 end
6627 #__END__
6628 # your data goes here
6629 # __DATA__ doesn't exist in Ruby
6630
6631 #CODE
6632 # get info about the script (size, date of last modification)
6633 kilosize = DATA.stat.size / 1024
6634 last_modif = DATA.stat.mtime
6635 puts "<P>Script size is #{kilosize}"
6636 puts "<P>Last script update: #{last_modif}"
6637 #__END__
6638 # DO NOT REMOVE THE PRECEEDING LINE.
6639 # Everything else in this file will be ignored.
6640 #CODE
6641
6642
6643 # @@PLEAC@@_7.7
6644 while line = gets do
6645 # do something with line.
6646 end
6647
6648 # or
6649 while gets do
6650 # do something with $_
6651 end
6652
6653 # or more rubyish
6654 $stdun.each do |line|
6655 # do stuff with line
6656 end
6657
6658
6659 # ARGF may makes this more easy
6660 # this is skipped if ARGV.size==0
6661 ARGV.each do |filename|
6662 # closing and exception handling are done by the block
6663 open(filename) do |fd|
6664 fd.each do |line|
6665 # do stuff with line
6666 end
6667 end rescue abort("can't open %s" % filename)
6668 end
6669
6670 # globbing is done in the Dir module
6671 ARGV = Dir["*.[Cch]"] if ARGV.empty?
6672
6673 # note: optparse is the preferred way to handle this
6674 if (ARGV[0] == '-c')
6675 chop_first += 1
6676 ARGV.shift
6677 end
6678
6679
6680 # processing numerical options
6681 if ARGV[0] =~ /^-(\d+)$/
6682 columns = $1
6683 ARGV.shift
6684 end
6685
6686 # again, better to use optparse:
6687 require 'optparse'
6688 nostdout = 0
6689 append = 0
6690 unbuffer = 0
6691 ignore_ints = 0
6692 ARGV.options do |opt|
6693 opt.on('-n') { nostdout +=1 }
6694 opt.on('-a') { append +=1 }
6695 opt.on('-u') { unbuffer +=1 }
6696 opt.on('-i') { ignore_ints +=1 }
6697 opt.parse!
6698 end or abort("usage: " + __FILE__ + " [-ainu] [filenames]")
6699
6700 # no need to do undef $/, we have File.read
6701 str = File.read(ARGV[0])
6702
6703 # again we have File.read
6704 str = File.read(ARGV[0])
6705
6706 # not sure what this should do:
6707 # I believe open the file, print filename, lineno and line:
6708 ARGF.each_with_index do |line, idx|
6709 print ARGF.filename, ":", idx, ";", line
6710 end
6711
6712 # print all the lines in every file passed via command line that contains login
6713 ARGF.each do |line|
6714 puts line if line =~ /login/
6715 end
6716 #
6717 # even this would fit
6718 #%ruby -ne "print if /f/" 2.log
6719 #
6720
6721 ARGF.each { |l| puts l.downcase! }
6722
6723 #------------------
6724 #!/usr/bin/ruby -p
6725 # just like perl's -p
6726 $_.downcase!
6727 #
6728
6729 # I don't know who should I trust.
6730 # perl's version splits on \w+ while python's on \w.
6731
6732 chunks = 0
6733
6734 File.read(ARGV[0]).split.each do |word|
6735 next if word =~ /^#/
6736 break if ["__DATA__", "__END__"].member? word
6737 chunks += 1
6738 end
6739
6740 print "Found ", chunks, " chunks\n"
6741
6742
6743 # @@PLEAC@@_7.8
6744 old = File.open(old_file)
6745 new = File.open(new_file, "w")
6746 while old.gets do
6747 # change $_, then...
6748 new.print $_
6749 end
6750 old.close
6751 new.close
6752 File.rename(old_file, "old.orig")
6753 File.rename(new_file, old_file)
6754
6755 while old.gets do
6756 if $. == 20 then # we are at the 20th line
6757 new.puts "Extra line 1"
6758 new.puts "Extra line 2"
6759 end
6760 new.print $_
6761 end
6762
6763 while old.gets do
6764 next if 20..30 # skip the 20th line to the 30th
6765 # Ruby (and Perl) permit to write if 20..30
6766 # instead of if (20 <= $.) and ($. <= 30)
6767 new.print $_
6768 end
6769
6770
6771 # @@PLEAC@@_7.9
6772 #% ruby -i.orig -pe 'FILTER COMMAND' file1 file2 file3 ...
6773 #
6774 #-----------------------------
6775 ##!/usr/bin/ruby -i.orig -p
6776 # filter commands go here
6777 #-----------------------------
6778
6779 #% ruby -pi.orig -e 'gsub!(/DATE/){Time.now)'
6780
6781 # effectively becomes:
6782 ARGV << 'I'
6783 oldfile = ""
6784 while gets
6785 if ARGF.filename != oldfile
6786 newfile = ARGF.filename
6787 File.rename(newfile, newfile + ".orig")
6788 $stdout = File.open(newfile,'w')
6789 oldfile = newfile
6790 end
6791 gsub!(/DATE/){Time.now}
6792 print
6793 end
6794 $stdout = STDOUT
6795 #-----------------------------
6796 #% ruby -i.old -pe 'gsub!(%r{\bhisvar\b}, 'hervar')' *.[Cchy]
6797
6798 #-----------------------------
6799 # set up to iterate over the *.c files in the current directory,
6800 # editing in place and saving the old file with a .orig extension
6801 $-i = '.orig' # set up -i mode
6802 ARGV.replace(Dir['*.[Cchy]'])
6803 while gets
6804 if $. == 1
6805 print "This line should appear at the top of each file\n"
6806 end
6807 gsub!(/\b(p)earl\b/i, '\1erl') # Correct typos, preserving case
6808 print
6809 ARGF.close if ARGF.eof
6810 end
6811
6812
6813 # @@PLEAC@@_7.10
6814 File.open('itest', 'r+') do |f| # open file for update
6815 lines = f.readlines # read into array of lines
6816 lines.each do |it| # modify lines
6817 it.gsub!(/foo/, 'QQQ')
6818 end
6819 f.pos = 0 # back to start
6820 f.print lines # write out modified lines
6821 f.truncate(f.pos) # truncate to new length
6822 end # file is automatically closed
6823 #-----------------------------
6824 File.open('itest', 'r+') do |f|
6825 out = ""
6826 f.each do |line|
6827 out << line.gsub(/DATE/) {Time.now}
6828 end
6829 f.pos = 0
6830 f.print out
6831 f.truncate(f.pos)
6832 end
6833
6834 # @@PLEAC@@_7.11
6835 File.open('infile', 'r+') do |f|
6836 f.flock File::LOCK_EX
6837 # update file
6838 end
6839 #-----------------------------
6840 File::LOCK_SH # shared lock (for reading)
6841 File::LOCK_EX # exclusive lock (for writing)
6842 File::LOCK_NB # non-blocking request
6843 File::LOCK_UN # free lock
6844 #-----------------------------
6845 unless f.flock File::LOCK_EX | File::LOCK_NB
6846 warn "can't get immediate lock: blocking ..."
6847 f.flock File::LOCK_EX
6848 end
6849 #-----------------------------
6850 File.open('numfile', File::RDWR|File::CREAT) do |f|
6851 f.flock(File::LOCK_EX)
6852 num = f.gets.to_i || 0
6853 f.pos = 0
6854 f.truncate 0
6855 f.puts num + 1q
6856 end
6857
6858
6859 # @@PLEAC@@_7.12
6860 output_handle.sync = true
6861 # Please note that like in Perl, $stderr is already unbuffered
6862 #-----------------------------
6863 #!/usr/bin/ruby -w
6864 # seeme - demo stdio output buffering
6865 $stdout.sync = ARGV.size > 0
6866 print "Now you don't see it..."
6867 sleep 2
6868 puts "now you do"
6869 #-----------------------------
6870 $stderr.sync = true
6871 afile.sync = false
6872 #-----------------------------
6873 # assume 'remote_con' is an interactive socket handle,
6874 # but 'disk_file' is a handle to a regular file.
6875 remote_con.sync = true # unbuffer for clarity
6876 disk_file.sync = false # buffered for speed
6877 #-----------------------------
6878 require 'socket'
6879 sock = TCPSocket.new('www.ruby-lang.org', 80)
6880 sock.sync = true
6881 sock.puts "GET /en/ HTTP/1.0 \n\n"
6882 resp = sock.read
6883 print "DOC IS: #{resp}\n"
6884
6885
6886 # @@PLEAC@@_7.13
6887 #-----------------------------
6888 # assumes fh1, fh2, fh2 are oen IO objects
6889 nfound = select([$stdin, fh1, fh2, fh3], nil, nil, 0)
6890 nfound[0].each do |file|
6891 case file
6892 when fh1
6893 # do something with fh1
6894 when fh2
6895 # do something with fh2
6896 when fh3
6897 # do something with fh3
6898 end
6899 end
6900 #-----------------------------
6901 input_files = []
6902 # repeat next line for all in-files to poll
6903 input_files << fh1
6904 if nfound = select(input_files, nil, nil, 0)
6905 # input ready on files in nfound[0]
6906 end
6907
6908
6909 # @@PLEAC@@_8.0
6910 #-----------------------------
6911 # datafile is a file or IO object
6912 datafile.readlines.each { |line|
6913 line.chomp!
6914 size = line.length
6915 puts size
6916 }
6917 #-----------------------------
6918 datafile.readlines.each { |line|
6919 puts line.chomp!.length
6920 }
6921 #-----------------------------
6922 lines = datafile.readlines
6923 #-----------------------------
6924 whole_file = file.read
6925 #-----------------------------
6926 # ruby -040 -e 'word = gets; puts "First word is #{word}"'
6927 #-----------------------------
6928 # ruby -ne 'BEGIN { $/="%%\n" }; $_.chomp; puts $_ if( $_=~/Unix/i)' fortune.dat
6929 #-----------------------------
6930 handle.print "one", "two", "three" # "onetwothree"
6931 puts "Baa baa black sheep." # sent to $stdout
6932 #-----------------------------
6933 buffer = handle.read(4096)
6934 rv = buffer.length
6935 #-----------------------------
6936 handle.truncate(length)
6937 open("/tmp#{$$}.pid", 'w') { |handle| handle.truncate(length) }
6938 #-----------------------------
6939 pos = datafile.pos # tell is an alias of pos
6940 puts "I'm #{pos} bytes from the start of datafile"
6941 #-----------------------------
6942 logfile.seek(0, IO::SEEK_END)
6943 datafile.seek(pos) # IO::SEEK_SET is the default
6944 out.seek(-20, IO::SEEK_CUR)
6945 #-----------------------------
6946 written = datafile.syswrite(mystring)
6947 raise RunTimeError unless written == mystring.length
6948 block = infile.sysread(256) # no equivalent to perl offset parameter in sysread
6949 puts "only read #{block.length} bytes" if 256 != block.length
6950 #-----------------------------
6951 pos = handle.sysseek(0, IO::SEEK_CUR) # don't change position
6952
6953
6954 # @@PLEAC@@_8.1
6955 while (line = fh.gets)
6956 line.chomp!
6957 nextline = nil
6958 line.gsub!(/\\$/) { |match| nextline = fh.gets; '' }
6959 if (nextline != nil)
6960 line += nextline
6961 redo
6962 end
6963 # process full record in line here
6964 end
6965 #-----------------------------
6966 # DISTFILES = $(DIST_COMMON) $(SOURCES) $(HEADERS) \
6967 # $(TEXINFOS) $(INFOS) $(MANS) $(DATA)
6968 # DEP_DISTFILES = $(DIST_COMMON) $(SOURCES) $(HEADERS) \
6969 # $(TEXINFOS) $(INFO_DEPS) $(MANS) $(DATA) \
6970 # $(EXTRA_DIST)
6971 #-----------------------------
6972 line.gsub!(/\\\s*$/, '') {
6973 # as before
6974 }
6975
6976
6977 # @@PLEAC@@_8.2
6978 #-----------------------------
6979 count = `wc -l < #{filename}`
6980 fail "wc failed: #{$?}" if $? != 0
6981 count.chomp!
6982 #-----------------------------
6983 count = 0
6984 File.open(file, 'r') { |fh|
6985 count += 1 while fh.gets
6986 }
6987 # count now holds the number of lines read
6988 #-----------------------------
6989 count = 0
6990 while (chunk = file.sysread(2**16))
6991 count += chunk.count("\n")
6992 end rescue EOFError
6993 #-----------------------------
6994 File.open(filename,'r') { |fh|
6995 count += 1 while fh.gets
6996 }
6997 # count now holds the number of lines read
6998 #-----------------------------
6999 # As ruby doesn't quite have an equivalent to using a for
7000 # statement as in perl, I threw this in
7001 count = File.readlines(filename).size
7002 #-----------------------------
7003 1 while file.gets
7004 count = $.
7005 #-----------------------------
7006 $/ = ''
7007 open(filename, 'r') { |fh|
7008 1 while fh.gets
7009 para_count = $.
7010 } rescue fail("can't open #{filename}: $!")
7011 #-----------------------------
7012
7013
7014 # ^^PLEAC^^_8.3
7015 #-----------------------------
7016 while (gets)
7017 split.each { |chunk|
7018 # do something with chunk
7019 }
7020 end
7021 #-----------------------------
7022 while (gets)
7023 gsub(/(\w[\w'-]*)/) { |word|
7024 # do something with word
7025 }
7026 end
7027 #-----------------------------
7028 # Make a word frequency count
7029 # normally hashes can be created using {} or just Hash.new
7030 # but we want the default value of an entry to be 0 instead
7031 # of nil. (nil can't be incremented)
7032 seen = Hash.new(0)
7033 while (gets)
7034 gsub(/(\w[\w'-]*)/) { |word|
7035 seen[word.downcase] += 1
7036 }
7037 end
7038 # output hash in a descending numeric sort of its values
7039 seen.sort { |a,b| b[1] <=> a[1] }.each do |k,v|
7040 printf("%5d %s\n", v, k )
7041 end
7042
7043 #-----------------------------
7044 # Line frequency count
7045 seen = Hash.new(0)
7046 while (gets)
7047 seen[$_.downcase] += 1
7048 end
7049 seen.sort { |a,b| b[1] <=> a[1] }.each do |k,v|
7050 printf("%5d %s\n", v, k )
7051 end
7052 #-----------------------------
7053
7054
7055 # @@PLEAC@@_8.4
7056 #-----------------------------
7057 # instead of file handle FILE, we can just
7058 # use a string containing the filename
7059 File.readlines(file).each { |line|
7060 # do something with line
7061 }
7062 #-----------------------------
7063 File.readlines(file).reverse_each { |line|
7064 # do something with line
7065 }
7066 #-----------------------------
7067 # the variable lines might have been created
7068 # this way
7069 # lines = File.readlines(file)
7070 #
7071 # normally one would use the reverse_each, but
7072 # if you insist on using a numerical index to
7073 # iterate over the lines array...
7074 (lines.size - 1).downto(0) { |i|
7075 line = lines[i]
7076 }
7077 #-----------------------------
7078 # the second readlines argument is a the
7079 # record separator $/, just like perl, a blank
7080 # separator splits the records into paragraphs
7081 File.readlines(file, '').each { |paragraph|
7082 # do something with paragraph
7083 puts "->Paragraph #{paragraph}"
7084 }
7085 #-----------------------------
7086
7087
7088 # @@PLEAC@@_8.6
7089
7090 $/ = "%\n";
7091 srand;
7092
7093 File.open('/usr/share/fortune/humorists').each do |line|
7094 adage = line if rand($.) < 1
7095 end
7096
7097 puts adage;
7098
7099
7100 # @@PLEAC@@_8.10
7101 begin
7102 fh = File.open(file, "r+")
7103 addr = fh.tell unless fh.eof while fh.gets
7104 fh.truncate(addr)
7105 rescue SystemCallError
7106 $stderr.puts "#$!"
7107 end
7108
7109
7110 # @@PLEAC@@_9.0
7111 entry = File.stat("/usr/bin/vi")
7112 entry = File.stat("/usr/bin")
7113 entry = File.stat(INFILE)
7114
7115 entry = File.stat("/usr/bin/vi")
7116 ctime = entry.ctime
7117 size = entry.size
7118
7119 f = File.open(filename, "r")
7120
7121 ## There is no -T equivalent in Ruby, but we can still test emptiness
7122 if test(?s, filename)
7123 puts "#{filename} doesn't have text in it."
7124 exit
7125 end
7126
7127 Dir.new("/usr/bin").each do |filename|
7128 puts "Inside /usr/bin is something called #{filename}"
7129 end
7130
7131
7132 # @@PLEAC@@_9.1
7133 file = File.stat("filename")
7134 readtime, writetime = file.atime, file.mtime
7135 file.utime(readtime, writetime)
7136
7137 SECONDS_PER_DAY = 60 * 60 * 24
7138 file = File.stat("filename")
7139 atime, mtime = file.atime, file.mtime
7140
7141 atime -= 7 * SECONDS_PER_DAY
7142 mtime -= 7 * SECONDS_PER_DAY
7143
7144 File.utime(atime, mtime, file)
7145 mtime = File.stat(file).mtime
7146 File.utime(Time.new, mtime, file)
7147 File.utime(Time.new, File.stat("testfile").mtime, file)
7148
7149 #-----------------------------
7150 #!/usr/bin/ruby -w
7151 ## uvi - vi a file without changing it's access times
7152
7153 if ARGV.length != 1
7154 puts "usage: uvi filename"
7155 exit
7156 end
7157 file = ARGV[0]
7158 atime, mtime = File.stat(file).atime, File.stat(file).mtime
7159 system(ENV["EDITOR"] || "vi", file)
7160 File.utime(atime, mtime, file)
7161 #-----------------------------
7162
7163
7164 # @@PLEAC@@_9.2
7165 File.unlink(FILENAME)
7166
7167 err_flg = false
7168 filenames.each do |file|
7169 begin
7170 File.unlink(file)
7171 rescue
7172 err_flg = $!
7173 end
7174 end
7175 err_flg and raise "Couldn't unlink all of #{filenames.join(" ")}: #{err_flg}"
7176
7177 File.unlink(file)
7178
7179 count = filenames.length
7180 filenames.each do |file|
7181 begin
7182 File.unlink(file)
7183 rescue
7184 count -= 1
7185 end
7186 end
7187 if count != filenames.length
7188 STDERR.puts "could only delete #{count} of #{filenames.length} files"
7189 end
7190
7191
7192 # @@PLEAC@@_9.3
7193 require "ftools"
7194 File.copy(oldfile, newfile)
7195
7196 infile = File.open(oldfile, "r")
7197 outfile = File.open(newfile, "w")
7198
7199 blksize = infile.stat.blksize
7200 # This doesn't handle partial writes or ^Z
7201 # like the Perl version does.
7202 while (line = infile.read(blksize))
7203 outfile.write(line)
7204 end
7205
7206 infile.close
7207 outfile.close
7208
7209 system("cp #{oldfile} #{newfile}") # unix
7210 system("copy #{oldfile} #{newfile}") # dos, vms
7211
7212 require "ftools"
7213 File.copy("datafile.dat", "datafile.bak")
7214 File.move("datafile.new", "datafile.dat")
7215
7216
7217 # @@PLEAC@@_9.4
7218 $seen = {} # must use global var to be seen inside of method below
7219
7220 def do_my_thing(filename)
7221 dev, ino = File.stat(filename).dev, File.stat(filename).ino
7222 unless $seen[[dev, ino]]
7223 # do something with $filename because we haven't
7224 # seen it before
7225 end
7226 $seen[[dev, ino]] = $seen[[dev, ino]].to_i + 1
7227 end
7228
7229 files.each do |filename|
7230 dev, ino = File.stat(filename).dev, File.stat(filename).ino
7231 if !$seen.has_key?([dev, ino])
7232 $seen[[dev, ino]] = []
7233 end
7234 $seen[[dev, ino]].push(filename)
7235 end
7236
7237 $seen.keys.sort.each do |devino|
7238 ino, dev = devino
7239 if $seen[devino].length > 1
7240 # $seen[devino] is a list of filenames for the same file
7241 end
7242 end
7243
7244
7245 # @@PLEAC@@_9.5
7246 Dir.open(dirname) do |dir|
7247 dir.each do |file|
7248 # do something with dirname/file
7249 puts file
7250 end
7251 end
7252 # Dir.close is automatic
7253
7254 # No -T equivalent in Ruby
7255
7256 dir.each do |file|
7257 next if file =~ /^\.\.?$/
7258 # ...
7259 end
7260
7261 def plainfiles(dir)
7262 dh = Dir.open(dir)
7263 dh.entries.grep(/^[^.]/).
7264 map {|file| "#{dir}/#{file}"}.
7265 find_all {|file| test(?f, file)}.
7266 sort
7267 end
7268
7269
7270 # @@PLEAC@@_9.6
7271 list = Dir.glob("*.c")
7272
7273 dir = Dir.open(path)
7274 files = dir.entries.grep(/\.c$/)
7275 dir.close
7276
7277 files = Dir.glob("*.c")
7278 files = Dir.open(path).entries.grep(/\.[ch]$/i)
7279
7280 dir = Dir.new(path)
7281 files = dir.entries.grep(/\.[ch]$/i)
7282
7283 begin
7284 d = Dir.open(dir)
7285 rescue Errno::ENOENT
7286 raise "Couldn't open #{dir} for reading: #{$!}"
7287 end
7288
7289 files = []
7290 d.each do |file|
7291 puts file
7292 next unless file =~ /\.[ch]$/i
7293
7294 filename = "#{dir}/#{file}"
7295 # There is no -T equivalent in Ruby, but we can still test emptiness
7296 files.push(filename) if test(?s, filename)
7297 end
7298
7299 dirs.entries.grep(/^\d+$/).
7300 map { |file| [file, "#{path}/#{file}"]} .
7301 select { |file| test(?d, file[1]) }.
7302 sort { |a,b| a[0] <=> b[0] }.
7303 map { |file| file[1] }
7304
7305
7306 # @@PLEAC@@_9.7
7307 require 'find'
7308 Find.find(dirlist) do |file|
7309 # do whatever
7310 end
7311
7312 require 'find'
7313 argv = ARGV.empty? ? %w{.} : ARGV
7314 Find.find(*argv) do |file|
7315 print file, (test(?d, file) ? "/\n" : "\n")
7316 end
7317
7318 require 'find'
7319 argv = ARGV.empty? ? %w{.} : ARGV
7320 sum = 0
7321 Find.find(*argv) do |file|
7322 size = test(?s, file) || 0
7323 sum += size
7324 end
7325 puts "#{argv.join(' ')} contains #{sum} bytes"
7326
7327 require 'find'
7328 argv = ARGV.empty? ? %w{.} : ARGV
7329 saved_size, saved_name = -1, ""
7330 Find.find(*argv) do |file|
7331 size = test(?s, file) || 0
7332 next unless test(?f, file) && size > saved_size
7333 saved_size = size
7334 saved_name = file
7335 end
7336 puts "Biggest file #{saved_name} in #{argv.join(' ')} is #{saved_size}"
7337
7338 require 'find'
7339 argv = ARGV.empty? ? %w{.} : ARGV
7340 age, name = nil
7341 Find.find(*argv) do |file|
7342 mtime = File.stat(file).mtime
7343 next if age && age > mtime
7344 age = mtime
7345 name = file
7346 end
7347 puts "#{name} #{age}"
7348
7349 #-----------------------------
7350 #!/usr/bin/ruby -w
7351 # fdirs - find all directories
7352 require 'find'
7353 argv = ARGV.empty? ? %w{.} : ARGV
7354 File.find(*argv) { |file| puts file if test(?d, file) }
7355 #-----------------------------
7356
7357
7358 # @@PLEAC@@_9.8
7359 require 'fileutils'
7360
7361 puts "Usage #{$0} dir ..." if ARGV.empty?
7362 ARGV.each do |dir|
7363 FileUtils.rmtree(dir)
7364 end
7365
7366
7367 # @@PLEAC@@_9.9
7368 require 'ftools'
7369 names.each do |file|
7370 newname = file
7371 begin
7372 File.move(file, newname)
7373 rescue Errno::EPERM
7374 $stderr.puts "Couldn't rename #{file} to #{newname}: #{$!}"
7375 end
7376 end
7377
7378 require 'ftools'
7379 op = ARGV.empty? ? (raise "Usage: rename expr [files]\n") : ARGV.shift
7380 argv = ARGV.empty? ? $stdin.readlines.map { |f| f.chomp } : ARGV
7381 argv.each do |file|
7382 was = file
7383 file = eval("file.#{op}")
7384 File.move(was, file) unless was == file
7385 end
7386
7387
7388 # @@PLEAC@@_9.10
7389 base = File.basename(path)
7390 dir = File.dirname(path)
7391 # ruby has no fileparse equivalent
7392 dir, base = File.split(path)
7393 ext = base.scan(/\..*$/).to_s
7394
7395 path = '/usr/lib/libc.a'
7396 file = File.basename(path)
7397 dir = File.dirname(path)
7398
7399 puts "dir is #{dir}, file is #{file}"
7400 # dir is /usr/lib, file is libc.a
7401
7402 path = '/usr/lib/libc.a'
7403 dir, filename = File.split(path)
7404 name, ext = filename.split(/(?=\.)/)
7405 puts "dir is #{dir}, name is #{name}, ext is #{ext}"
7406 # NOTE: The Ruby code prints
7407 # dir is /usr/lib, name is libc, extension is .a
7408 # while the Perl code prints a '/' after the directory name
7409 # dir is /usr/lib/, name is libc, extension is .a
7410
7411 # No fileparse_set_fstype() equivalent in ruby
7412
7413 def extension(path)
7414 ext = path.scan(/\..*$/).to_s
7415 ext.sub(/^\./, "")
7416 end
7417
7418
7419 # @@PLEAC@@_9.11
7420 #-----------------------------
7421 #!/usr/bin/ruby -w
7422 # symirror - build spectral forest of symlinks
7423
7424 require 'find'
7425 require 'fileutils'
7426
7427 raise "usage: #{$0} realdir mirrordir" unless ARGV.size == 2
7428
7429 srcdir,dstdir = ARGV
7430 srcmode = File::stat(srcdir).mode
7431 Dir.mkdir(dstdir, srcmode & 07777) unless test(?d, dstdir)
7432
7433 # fix relative paths
7434 Dir.chdir(srcdir) {srcdir = Dir.pwd}
7435 Dir.chdir(dstdir) {dstdir = Dir.pwd}
7436
7437 Find.find(srcdir) do |srcfile|
7438 if test(?d, srcfile)
7439 dest = srcfile.sub(/^#{srcdir}/, dstdir)
7440 dmode = File::stat(srcfile).mode & 07777
7441 Dir.mkdir(dest, dmode) unless test(?d, dest)
7442 a = Dir["#{srcfile}/*"].reject{|f| test(?d, f)}
7443 FileUtils.ln_s(a, dest)
7444 end
7445 end
7446
7447
7448 # @@PLEAC@@_9.12
7449 # we use the Getopt/Declare library here for convenience:
7450 # http://raa.ruby-lang.org/project/getoptdeclare/
7451 #-----------------------------
7452 #!/usr/bin/ruby -w
7453 # lst - list sorted directory contents (depth first)
7454
7455 require 'find'
7456 require 'etc'
7457 require "Getopt/Declare"
7458
7459 # Note: in the option-spec below there must by at least one hard
7460 # tab in between each -option and its description. For example
7461 # -i <tab> read from stdin
7462
7463 opts = Getopt::Declare.new(<<'EOPARAM')
7464 ============
7465 Input Format:
7466 -i read from stdin
7467 ============
7468 Output Format:
7469 -l long listing
7470 -r reverse listing
7471 ============
7472 Sort on: (one of)
7473 -m mtime (modify time - default)
7474 {$sort_criteria = :mtime}
7475 -u atime (access time)
7476 {$sort_criteria = :atime}
7477 -c ctime (inode change time)
7478 {$sort_criteria = :ctime}
7479 -s size
7480 {$sort_criteria = :size}
7481 [mutex: -m -u -c -s]
7482
7483 EOPARAM
7484
7485 $sort_criteria ||= :mtime
7486 files = {}
7487 DIRS = opts['-i'] ? $stdin.readlines.map{|f|f.chomp!} : ARGV
7488 DIRS.each do |dir|
7489 Find.find(dir) do |ent|
7490 files[ent] = File::stat(ent)
7491 end
7492 end
7493 entries = files.keys.sort_by{|f| files[f].send($sort_criteria)}
7494 entries = entries.reverse unless opts['-r']
7495
7496 entries.each do |ent|
7497 unless opts['-l']
7498 puts ent
7499 next
7500 end
7501 stats = files[ent]
7502 ftime = stats.send($sort_criteria == :size ? :mtime : $sort_criteria)
7503 printf "%6d %04o %6d %8s %8s %8d %s %s\n",
7504 stats.ino,
7505 stats.mode & 07777,
7506 stats.nlink,
7507 ETC::PASSWD[stats.uid].name,
7508 ETC::GROUP[stats.gid].name,
7509 stats.size,
7510 ftime.strftime("%a %b %d %H:%M:%S %Y"),
7511 ent
7512 end
7513
7514
7515 # @@PLEAC@@_10.0
7516 def hello
7517 $greeted += 1 # in Ruby, a variable beginning with $ is global (can be any type of course)
7518 puts "hi there!"
7519 end
7520
7521 # We need to initialize $greeted before it can be used, because "+=" is waiting a Numeric object
7522 $greeted = 0
7523 hello # note that appending () is optional to function calls with no parameters
7524
7525
7526 # @@PLEAC@@_10.1
7527 # In Ruby, parameters are named anyway
7528 def hypotenuse(side1, side2)
7529 Math.sqrt(side1**2 + side2**2) # the sqrt function comes from the Math module
7530 end
7531 diag = hypotenuse(3, 4)
7532
7533 puts hypotenuse(3, 4)
7534
7535 a = [3, 4]
7536 print hypotenuse(*a) # the star operator will magically convert an Array into a "tuple"
7537
7538 both = men + women
7539
7540 # In Ruby, all objects are references, so the same problem arises; we then return a new object
7541 nums = [1.4, 3.5, 6.7]
7542 def int_all(n)
7543 n.collect { |v| v.to_i }
7544 end
7545 ints = int_all(nums)
7546
7547 nums = [1.4, 3.5, 6.7]
7548 def trunc_em(n)
7549 n.collect! { |v| v.to_i } # the bang-version of collect modifies the object
7550 end
7551 trunc_em(nums)
7552
7553 # Ruby has two chomp version:
7554 # ``chomp'' chomps the record separator and returns what's expected
7555 # ``chomp!'' does the same but also modifies the parameter object
7556
7557
7558 # @@PLEAC@@_10.2
7559 def somefunc
7560 variable = something # variable is local by default
7561 end
7562
7563 name, age = ARGV
7564 start = fetch_time
7565
7566 a, b = pair # will succeed if pair is an Array object (like ARGV is)
7567 c = fetch_time
7568
7569 # In ruby, run_check can't access a, b, or c until they are
7570 # explicitely defined global (using leading $), even if they are
7571 # both defined in the same scope
7572
7573 def check_x(x)
7574 y = "whatever"
7575 run_check
7576 if $condition
7577 puts "got $x"
7578 end
7579 end
7580
7581 # The following will keep a reference to the array, though the
7582 # results will be slightly different from perl: the last element
7583 # of $global_array will be itself an array
7584 def save_array(ary)
7585 $global_array << ary
7586 end
7587
7588 # The following gives the same results as in Perl for $global_array,
7589 # though it doesn't illustrate anymore the way to keep a reference
7590 # to an object: $global_array is extended with the elements of ary
7591 def save_array(ary)
7592 $global_array += ary
7593 end
7594
7595
7596 # @@PLEAC@@_10.3
7597 # In Ruby, AFAIK a method cannot access "local variables" defined
7598 # upper scope; mostly because everything is an object, so you'll
7599 # do the same by defining an attribute or a static attribute
7600
7601 # In Ruby the BEGIN also exists:
7602 BEGIN { puts "hello from BEGIN" }
7603 puts "hello from main"
7604 BEGIN { puts "hello from 2nd BEGIN" }
7605 # gives:
7606 # hello from BEGIN
7607 # hello from 2nd BEGIN
7608 # hello from main
7609
7610 # In Ruby, it can be written as a static method and a static
7611 # variable
7612 class Counter
7613 @@counter = 0
7614 def Counter.next_counter; @@counter += 1; end
7615 end
7616
7617 # There is no need of BEGIN since the variable will get
7618 # initialized when parsing
7619 class Counter
7620 @@counter = 42
7621 def Counter.next_counter; @@counter += 1; end
7622 def Counter.prev_counter; @@counter -= 1; end
7623 end
7624
7625
7626 # @@PLEAC@@_10.4
7627 # You can either get the whole trace as an array of strings, each
7628 # string telling which file, line and method is calling:
7629 caller
7630
7631 # ...or only the last caller
7632 caller[0]
7633
7634 # We need to extract just the method name of the backtrace:
7635 def whoami; caller()[0] =~ /in `([^']+)'/ ? $1 : '(anonymous)'; end
7636 def whowasi; caller()[1] =~ /in `([^']+)'/ ? $1 : '(anonymous)'; end
7637
7638
7639 # @@PLEAC@@_10.5
7640 # In Ruby, every value is a reference on an object, thus there is
7641 # no such problem
7642 array_diff(array1, array2)
7643
7644 def add_vecpair(a1, a2)
7645 results = []
7646 a1.each_index { |i| results << (a1[i] + a2[i]) }
7647 results
7648 end
7649 a = [1, 2]
7650 b = [5, 8]
7651 c = add_vecpair(a, b)
7652 p c
7653
7654 # Add this to the beginning of the function to check if we were
7655 # given two arrays
7656 a1.type == Array && a2.type == Array or
7657 raise "usage: add_vecpair array1 array2 (was used with: #{a1.type} #{a2.type})"
7658
7659
7660 # @@PLEAC@@_10.6
7661 # There is no return context in Ruby
7662
7663
7664 # @@PLEAC@@_10.7
7665 # Like in Perl, we need to fake with a hash, but it's dirty :-(
7666 def thefunc(param_args)
7667 args = { 'INCREMENT' => '10s', 'FINISH' => '0', 'START' => 0 }
7668 args.update(param_args)
7669 if (args['INCREMENT'] =~ /m$/ )
7670 # .....
7671 end
7672 end
7673
7674 thefunc({ 'INCREMENT' => '20s', 'START' => '+5m', 'FINISH' => '+30m' })
7675 thefunc({})
7676
7677
7678 # @@PLEAC@@_10.8
7679 # there is no "undef" direct equivalent but there is the slice equiv:
7680 a, c = func.indexes(0, 2)
7681
7682
7683 # @@PLEAC@@_10.9
7684 # Ruby has no such limitation:
7685 def somefunc
7686 ary = []
7687 hash = {}
7688 # ...
7689 return ary, hash
7690 end
7691 arr, dict = somefunc
7692
7693 array_of_hashes = fn
7694 h1, h2, h3 = fn
7695
7696
7697 # @@PLEAC@@_10.10
7698 return
7699 # or (equivalent)
7700 return nil
7701
7702
7703 # @@PLEAC@@_10.11
7704 # You can't prototype in Ruby regarding types :-(
7705 # Though, you can force the number of arguments:
7706 def func_with_no_arg; end
7707 def func_with_no_arg(); end
7708 def func_with_one_arg(a1); end
7709 def func_with_two_args(a1, a2); end
7710 def func_with_any_number_of_args(*args); end
7711
7712
7713 # @@PLEAC@@_10.12
7714 raise "some message" # raise exception
7715
7716 begin
7717 val = func
7718 rescue Exception => msg
7719 $stderr.puts "func raised an exception: #{msg}"
7720 end
7721
7722 # In Ruby the rescue statement uses an exception class, every
7723 # exception which is not matched is still continuing
7724 begin
7725 val = func
7726 rescue FullMoonError
7727 ...
7728 end
7729
7730
7731 # @@PLEAC@@_10.13
7732 # Saving Global Values
7733 # Of course we can just save the value and restore it later:
7734 def print_age
7735 puts "Age is #{$age}"
7736 end
7737
7738 $age = 18 # global variable
7739 print_age()
7740 if condition
7741 safeage = $age
7742 $age = 23
7743 print_age()
7744 $age = safeage
7745 end
7746
7747 # We can also use a method that saves the global variable and
7748 # restores it automatically when the block is left:
7749
7750 def local(var)
7751 eval("save = #{var.id2name}")
7752 begin
7753 result = yield
7754 ensure
7755 # we want to call this even if we got an exception
7756 eval("#{var.id2name} = save")
7757 end
7758 result
7759 end
7760
7761 condition = true
7762 $age = 18
7763 print_age()
7764 if condition
7765 local(:$age) {
7766 $age = 23
7767 print_age()
7768 }
7769 end
7770 print_age()
7771
7772 # There is no need to use local() for filehandles or directory
7773 # handles in ruby because filehandles are normal objects.
7774
7775
7776 # @@PLEAC@@_10.14
7777 # In Ruby you may redefine a method [but not overload it :-(]
7778 # just by defining again with the same name.
7779 def foo; puts 'foo'; end
7780 def foo; puts 'bar'; end
7781 foo
7782 #=> bar
7783
7784 # You can also take a reference to an existing method before
7785 # redefining a new one, using the `alias' keyword
7786 def foo; puts 'foo'; end
7787 alias foo_orig foo
7788 def foo; puts 'bar'; end
7789 foo_orig
7790 foo
7791 #=> foo
7792 #=> bar
7793
7794 # AFAIK, there is no direct way to create a new method whose name
7795 # comes from a variable, so use "eval"
7796 colors = %w(red blue green yellow orange purple violet)
7797 colors.each { |c|
7798 eval <<-EOS
7799 def #{c}(*a)
7800 "<FONT COLOR='#{c}'>" + a.to_s + "</FONT>"
7801 end
7802 EOS
7803 }
7804
7805
7806 # @@PLEAC@@_10.15
7807 def method_missing(name, *args)
7808 "<FONT COLOR='#{name}'>" + args.join(' ') + "</FONT>"
7809 end
7810 puts chartreuse("stuff")
7811
7812
7813 # @@PLEAC@@_10.16
7814 def outer(arg)
7815 x = arg + 35
7816 inner = proc { x * 19 }
7817 x + inner.call()
7818 end
7819
7820
7821 # @@PLEAC@@_10.17
7822 #!/usr/bin/ruby -w
7823 # mailsort - sort mbox by different criteria
7824 require 'English'
7825 require 'Date'
7826
7827 # Objects of class Mail represent a single mail.
7828 class Mail
7829 attr_accessor :no
7830 attr_accessor :subject
7831 attr_accessor :fulltext
7832 attr_accessor :date
7833
7834 def initialize
7835 @fulltext = ""
7836 @subject = ""
7837 end
7838
7839 def append(para)
7840 @fulltext << para
7841 end
7842
7843 # this is called if you call puts(mail)
7844 def to_s
7845 @fulltext
7846 end
7847 end
7848
7849 # represents a list of mails.
7850 class Mailbox < Array
7851
7852 Subjectpattern = Regexp.new('Subject:\s*(?:Re:\s*)*(.*)\n')
7853 Datepattern = Regexp.new('Date:\s*(.*)\n')
7854
7855 # reads mails from open file and stores them
7856 def read(file)
7857 $INPUT_RECORD_SEPARATOR = '' # paragraph reads
7858 msgno = -1
7859 file.each { |para|
7860 if para =~ /^From/
7861 mail = Mail.new
7862 mail.no = (msgno += 1)
7863 md = Subjectpattern.match(para)
7864 if md
7865 mail.subject = md[1]
7866 end
7867 md = Datepattern.match(para)
7868 if md
7869 mail.date = DateTime.parse(md[1])
7870 else
7871 mail.date = DateTime.now
7872 end
7873 self.push(mail)
7874 end
7875 mail.append(para) if mail
7876 }
7877 end
7878
7879 def sort_by_subject_and_no
7880 self.sort_by { |m|
7881 [m.subject, m.no]
7882 }
7883 end
7884
7885 # sorts by a list of attributs of mail, given as symbols
7886 def sort_by_attributs(*attrs)
7887 # you can sort an Enumerable by an array of
7888 # values, they would be compared
7889 # from ary[0] to ary[n]t, say:
7890 # ['b',1] > ['a',10] > ['a',9]
7891 self.sort_by { |elem|
7892 attrs.map { |attr|
7893 elem.send(attr)
7894 }
7895 }
7896 end
7897
7898 end
7899
7900 mailbox = Mailbox.new
7901 mailbox.read(ARGF)
7902
7903 # print only subjects sorted by subject and number
7904 for m in mailbox.sort_by_subject_and_no
7905 puts(m.subject)
7906 end
7907
7908 # print complete mails sorted by date, then subject, then number
7909 for m in mailbox.sort_by_attributs(:date, :subject)
7910 puts(m)
7911 end
7912
7913
7914 # @@PLEAC@@_11.7
7915 def mkcounter(count)
7916 start = count
7917 bundle = {
7918 "NEXT" => proc { count += 1 },
7919 "PREV" => proc { count -= 1 },
7920 "RESET" => proc { count = start }
7921 }
7922 bundle["LAST"] = bundle["PREV"]
7923 return bundle
7924 end
7925
7926 c1 = mkcounter(20)
7927 c2 = mkcounter(77)
7928
7929 puts "next c1: #{c1["NEXT"].call}" # 21
7930 puts "next c2: #{c2["NEXT"].call}" # 78
7931 puts "next c1: #{c1["NEXT"].call}" # 22
7932 puts "last c1: #{c1["PREV"].call}" # 21
7933 puts "last c1: #{c1["LAST"].call}" # 20
7934 puts "old c2: #{c2["RESET"].call}" # 77
7935
7936
7937 # @@PLEAC@@_11.15
7938 class Binary_tree
7939 def initialize(val)
7940 @value = val
7941 @left = nil
7942 @right = nil
7943 end
7944
7945 # insert given value into proper point of
7946 # provided tree. If no tree provided,
7947 # use implicit pass by reference aspect of @_
7948 # to fill one in for our caller.
7949 def insert(val)
7950 if val < @value then
7951 if @left then
7952 @left.insert(val)
7953 else
7954 @left = Binary_tree.new(val)
7955 end
7956 elsif val > @value then
7957 if @right then
7958 @right.insert(val)
7959 else
7960 @right = Binary_tree.new(val)
7961 end
7962 else
7963 puts "double"
7964 # do nothing, no double values
7965 end
7966 end
7967
7968 # recurse on left child,
7969 # then show current value,
7970 # then recurse on right child.
7971 def in_order
7972 @left.in_order if @left
7973 print @value, " "
7974 @right.in_order if @right
7975 end
7976
7977 # show current value,
7978 # then recurse on left child,
7979 # then recurse on right child.
7980 def pre_order
7981 print @value, " "
7982 @left.pre_order if @left
7983 @right.pre_order if @right
7984 end
7985
7986 # recurse on left child,
7987 # then recurse on right child,
7988 # then show current value.
7989 def post_order
7990 @left.post_order if @left
7991 @right.post_order if @right
7992 print @value, " "
7993 end
7994
7995 # find out whether provided value is in the tree.
7996 # if so, return the node at which the value was found.
7997 # cut down search time by only looking in the correct
7998 # branch, based on current value.
7999 def search(val)
8000 if val == @value then
8001 return self
8002 elsif val < @value then
8003 return @left.search(val) if @left
8004 return nil
8005 else
8006 return @right.search(val) if @right
8007 return nil
8008 end
8009 end
8010 end
8011
8012 # first generate 20 random inserts
8013 test = Binary_tree.new(0)
8014 for a in 0..20
8015 test.insert(rand(1000))
8016 end
8017
8018 # now dump out the tree all three ways
8019 print "Pre order: "; test.pre_order; puts ""
8020 print "In order: "; test.in_order; puts ""
8021 print "Post order: "; test.post_order; puts ""
8022
8023 print "search?"
8024 while gets
8025 print test.search($_.to_i)
8026 print "\nsearch?"
8027 end
8028
8029
8030 # @@PLEAC@@_12.0
8031 # class and module names need to have the first letter capitalized
8032 module Alpha
8033 NAME = 'first'
8034 end
8035 module Omega
8036 NAME = 'last'
8037 end
8038 puts "Alpha is #{Alpha::NAME}, Omega is #{Omega::NAME}"
8039
8040 # ruby doesn't differentiate beteen compile-time and run-time
8041 require 'getoptlong.rb'
8042 require 'getoptlong' # assumes the .rb
8043 require 'cards/poker.rb'
8044 require 'cards/poker' # assumes the .rb
8045 load 'cards/poker' # require only loads the file once
8046
8047 module Cards
8048 module Poker
8049 @card_deck = Array.new # or @card_deck = []
8050 def shuffle
8051 end
8052 end
8053 end
8054
8055
8056 # @@PLEAC@@_12.1
8057 # a module exports all of its functions
8058 module Your_Module
8059 def self.function
8060 # this would be called as Your_Module.function
8061 end
8062
8063 def Your_Module.another
8064 # this is the same as above, but more specific
8065 end
8066 end
8067
8068 # @@PLEAC@@_12.2
8069 begin
8070 require 'nonexistent'
8071 rescue LoadError
8072 puts "Couldn't load #{$!}" # $! contains the last error string
8073 end
8074
8075 # @@PLEAC@@_12.4
8076 # module variables are private unless access functions are defined
8077 module Alpha
8078 @aa = 10
8079 @bb = 11
8080
8081 def self.put_aa
8082 puts @aa
8083 end
8084
8085 def self.bb=(val)
8086 @bb = val
8087 end
8088 end
8089
8090 Alpha.bb = 12
8091 # Alpha.aa = 10 # error, no aa=method
8092
8093
8094 # @@PLEAC@@_12.5
8095 # caller provides a backtrace of the call stack
8096 module MyModule
8097 def find_caller
8098 caller
8099 end
8100
8101 def find_caller2(i)
8102 caller(i) # an argument limits the size of the stack returned
8103 end
8104 end
8105
8106
8107 # @@PLEAC@@_12.6
8108 BEGIN {
8109 $logfile = '/tmp/mylog' unless defined? $logfile
8110 $LF = File.open($logfile, 'a')
8111 }
8112
8113 module Logger
8114 def self.logmsg(msg)
8115 $LF.puts msg
8116 end
8117
8118 logmsg('startup')
8119 end
8120
8121 END {
8122 Logger::logmsg('shutdown')
8123 $LF.close
8124 }
8125
8126
8127 # @@PLEAC@@_12.7
8128 #-----------------------------
8129 # results may be different on your system
8130 # % ruby -e "$LOAD_PATH.each_index { |i| printf("%d %s\n", i, $LOAD_PATH[i] }
8131 #0 /usr/local/lib/site_ruby/1.6
8132 #1 /usr/local/lib/site_ruby/1.6/i386-linux
8133 #2 /usr/local/lib/site_ruby/
8134 #3 /usr/lib/ruby/1.6
8135 #4 /usr/lib/ruby/1.6/i136-linux
8136 #5 .
8137 #-----------------------------
8138 # syntax for sh, bash, ksh, or zsh
8139 #$ export RUBYLIB=$HOME/rubylib
8140
8141 # syntax for csh or tcsh
8142 # % setenv RUBYLIB ~/rubylib
8143 #-----------------------------
8144 $LOAD_PATH.unshift "/projects/spectre/lib";
8145
8146
8147 # @@PLEAC@@_12.8
8148 # equivalents in ruby are mkmf, SWIG, or Ruby/DL depending on usage
8149
8150
8151 # @@PLEAC@@_12.9
8152 # no equivalent in ruby
8153
8154
8155 # @@PLEAC@@_12.10
8156 # no equivalent in ruby
8157
8158
8159 # @@PLEAC@@_12.11
8160 module FineTime
8161 def self.time
8162 # to be defined later
8163 end
8164 end
8165
8166
8167 module FineTime
8168 def self.time
8169 "its a fine time"
8170 end
8171 end
8172
8173 puts FineTime.time #=> "its a fine time"
8174
8175
8176 # @@PLEAC@@_12.12
8177 def even_only(n)
8178 raise "#{n} is not even" if (n & 1) != 0 # one way to test
8179 # ...
8180 end
8181 def even_only(n)
8182 $stderr.puts "#{n} is not even" if (n & 1) != 0
8183 # ...
8184 end
8185
8186
8187 # @@PLEAC@@_12.17
8188 # The library archive for ruby is called Ruby Application archive,
8189 # or shorter RAA, and can be found at http://raa.ruby-lang.org.
8190 # A typical library is installed like this:
8191 # % gunzip some-module-4.54.tar.gz
8192 # % tar xf some-module-4.54.tar
8193 # % cd some-module-4.54.tar
8194 # % ruby install.rb config
8195 # % ruby install.rb setup
8196 # get superuser previleges here if needed for next step
8197 # % ruby install.rb install
8198
8199 # Some modules use a different process,
8200 # you should find details in the documentation
8201 # Here is an example of such a different process
8202 # % ruby extconf.rb
8203 # % make
8204 # % make install
8205
8206 # If you want the module installed in your own directory:
8207 # For ruby version specific libraries
8208 # % ruby install.rb config --site-ruby=~/lib
8209 # For version independent libraries
8210 # % ruby install.rb config --site-ruby-common=~/lib
8211
8212 # Information about possible options for config
8213 # % ruby install.rb --help
8214
8215 # If you have your own complete distribution
8216 # % ruby install.rb --prefix=path=~/ruby-private
8217
8218
8219 # @@PLEAC@@_13.0
8220 # Classes and objects in Ruby are rather straigthforward
8221 class Person
8222 # Class variables (also called static attributes) are prefixed by @@
8223 @@person_counter=0
8224
8225 # object constructor
8226 def initialize(age, name, alive = true) # Default arg like in C++
8227 @age, @name, @alive = age, name, alive # Object attributes are prefixed by '@'
8228 @@person_counter += 1
8229 # There is no '++' operator in Ruby. The '++'/'--' operators are in fact
8230 # hidden assignments which affect variables, not objects. You cannot accomplish
8231 # assignment via method. Since everything in Ruby is object, '++' and '--'
8232 # contradict Ruby OO ideology. Instead '-=' and '+=' are used.
8233 end
8234
8235 attr_accessor :name, :age # This creates setter and getter methods for @name
8236 # and @age. See 13.3 for detailes.
8237
8238 # methods modifying the receiver object usually have the '!' suffix
8239 def die!
8240 @alive = false
8241 puts "#{@name} has died at the age of #{@age}."
8242 @alive
8243 end
8244
8245 def kill(anotherPerson)
8246 print @name, ' is killing ', anotherPerson.name, ".\n"
8247 anotherPerson.die!
8248 end
8249
8250 # methods used as queries
8251 # usually have the '?' suffix
8252 def alive?
8253 @alive && true
8254 end
8255
8256 def year_of_birth
8257 Time.now.year - @age
8258 end
8259
8260 # Class method (also called static method)
8261 def Person.number_of_people
8262 @@person_counter
8263 end
8264 end
8265
8266 # Using the class:
8267 # Create objects of class Person
8268 lecter = Person.new(47, 'Hannibal')
8269 starling = Person.new(29, 'Clarice', true)
8270 pazzi = Person.new(40, 'Rinaldo', true)
8271
8272 # Calling a class method
8273 print "There are ", Person.number_of_people, " Person objects\n"
8274
8275 print pazzi.name, ' is ', (pazzi.alive?) ? 'alive' : 'dead', ".\n"
8276 lecter.kill(pazzi)
8277 print pazzi.name, ' is ', (pazzi.alive?) ? 'alive' : 'dead', ".\n"
8278
8279 print starling.name , ' was born in ', starling.year_of_birth, "\n"
8280
8281
8282 # @@PLEAC@@_13.1
8283 # If you don't need any initialisation in the constructor,
8284 # you don't need to write a constructor.
8285 class MyClass
8286 end
8287
8288 class MyClass
8289 def initialize
8290 @start = Time.new
8291 @age = 0
8292 end
8293 end
8294
8295 class MyClass
8296 def initialize(inithash)
8297 @start = Time.new
8298 @age = 0
8299 for key, value in inithash
8300 instance_variable_set("@#{key}", value)
8301 end
8302 end
8303 end
8304
8305 # @@PLEAC@@_13.2
8306 # Objects are destroyed by the garbage collector.
8307 # The time of destroying is not predictable.
8308 # The ruby garbage collector can handle circular references,
8309 # so there is no need to write destructor for that.
8310
8311 # There is no direct support for destructor.
8312 # You can call a custom function, or more specific a proc object, when the
8313 # garbage collector is about to destruct the object, but it is unpredictable
8314 # when this occurs.
8315 # Also if such a finalizer object has a reference to the orignal object,
8316 # this may prevent the original object to get garbage collected.
8317 # Because of this problem the finalize method below is
8318 # a class method and not a instance method.
8319 # So if you need to free resources for an object, like
8320 # closing a socket or kill a spawned subprocess,
8321 # you should do it explicitly.
8322
8323 class MyClass
8324 def initialize
8325 ObjectSpace.define_finalizer(self,
8326 self.class.method(:finalize).to_proc)
8327 end
8328 def MyClass.finalize(id)
8329 puts "Object #{id} dying at #{Time.new}"
8330 end
8331 end
8332
8333 # test code
8334 3.times {
8335 MyClass.new
8336 }
8337 ObjectSpace.garbage_collect
8338
8339
8340 # @@PLEAC@@_13.3
8341 # You can write getter and setter methods in a natural way:
8342 class Person
8343 def name
8344 @name
8345 end
8346 def name=(name)
8347 @name = name
8348 end
8349 end
8350
8351 # But there is a better and shorter way
8352 class Person
8353 attr_reader :age
8354 attr_writer :name
8355 # attr_reader and attr_writer are actually methods in class Class
8356 # which set getter and setter methods for you.
8357 end
8358
8359 # There is also attr_accessor to create both setters and getters
8360 class Person
8361 attr_accessor :age, :name
8362 end
8363
8364
8365 # @@PLEAC@@_13.4
8366 class Person
8367 # Class variables (also called static attributes) are prefixed by @@
8368 @@person_counter = 0
8369
8370 def Person.population
8371 @@person_counter
8372 end
8373 def initialize
8374 @@person_counter += 1
8375 ObjectSpace.define_finalizer(self,
8376 self.class.method(:finalize).to_proc)
8377 end
8378 def Person.finalize(id)
8379 @@person_counter -= 1
8380 end
8381 end
8382 people = []
8383 10.times {
8384 people.push(Person.new)
8385 }
8386 printf("There are %d people alive", Person.population)
8387
8388
8389 FixedArray.class_max_bounds = 100
8390 alpha = FixedArray.new
8391 puts "Bound on alpha is #{alpha.max_bounds}"
8392
8393 beta = FixedArray.new
8394 beta.max_bounds = 50 # calls the instance method
8395 beta.class.class_max_bounds = 50 # alternative, calls the class method
8396 puts "Bound on alpha is #{alpha.max_bounds}"
8397
8398 class FixedArray
8399 @@bounds = 7
8400
8401 def max_bounds
8402 @@max_bounds
8403 end
8404 # instance method, which sets the class variable
8405 def max_bounds=(value)
8406 @@max_bounds = value
8407 end
8408 # class method. This can only be called on a class,
8409 # but not on the instances
8410 def FixedArray.class_max_bounds=(value)
8411 @@max_bounds = value
8412 end
8413 end
8414
8415
8416 # @@PLEAC@@_13.5
8417 PersonStruct = Struct.new("Person", :name, :age, :peers)
8418 # creates a class "Person::Struct", which is accessiable with the
8419 # constant "PersonStruct"
8420 p = PersonStruct.new
8421 p = Struct::Person.new # alternative using the classname
8422 p.name = "Jason Smythe"
8423 p.age = 13
8424 p.peers = ["Wilbur", "Ralph", "Fred"]
8425 p[:peers] = ["Wilbur", "Ralph", "Fred"] # alternative access using symbol
8426 p["peers"] = ["Wilbur", "Ralph", "Fred"] # alternative access using name of field
8427 p[2] = ["Wilbur", "Ralph", "Fred"] # alternative access using index of field
8428 puts "At age #{p.age}, #{p.name}'s first friend is #{p.peers[0]}"
8429
8430 # The fields of a struct have no special type, like other ruby variables
8431 # you can put any objects in. Therefore the discussions how to specify
8432 # the types of the fields do not apply to ruby.
8433
8434 FamilyStruct = Struct.new("Family", :head, :address, :members)
8435 folks = FamilyStruct.new
8436 folks.head = PersonStruct.new
8437 dad = folks.head
8438 dad.name = "John"
8439 dad.age = 34
8440
8441 # supply of own accessor method for the struct for error checking
8442 class PersonStruct
8443 def age=(value)
8444 if !value.kind_of?(Integer)
8445 raise(ArgumentError, "Age #{value} isn't an Integer")
8446 elsif value > 150
8447 raise(ArgumentError, "Age #{value} is unreasonable")
8448 end
8449 @age = value
8450 end
8451 end
8452
8453
8454 # @@PLEAC@@_13.6
8455 # The ruby Object class defines a dup and a clone method.
8456 # The dup method is recommended for prototype object creation.
8457 # The default implementation makes a shallow copy,
8458 # but each class can override it, for example to make a deep copy.
8459
8460 # If you want to call 'new' directly on the instances,
8461 # you can create a instance method "new", which returns a new duplicate.
8462 # This method is distinct from the class method new.
8463 #
8464 class A
8465 def new
8466 dup
8467 end
8468 end
8469
8470 ob1 = A.new
8471 # later on
8472 ob2 = ob1.new
8473
8474
8475 # @@PLEAC@@_13.7
8476 methname = 'flicker'
8477 obj.send(methname, 10) # calls obj.flicker(10)
8478
8479 # call three methods on the object, by name
8480 ['start', 'run', 'stop'].each do |method_string|
8481 obj.send(method_string)
8482 end
8483
8484 # Another way is to create a Method object
8485 method_obj = obj.method('flicker')
8486 # And then call it
8487 method_obj.call(10)
8488
8489
8490 # @@PLEAC@@_13.8
8491 # All classes in Ruby inherit from class Object
8492 # and thus all objects share methods defined in this class
8493
8494 # the class of the object
8495 puts any_object.type
8496
8497 # Ruby classes are actually objects of class Class and they
8498 # respond to methods defined in Object class as well
8499
8500 # the superclass of this class
8501 puts any_object.class.superclass
8502
8503 # ask an object whether it is an instance of particular class
8504 n = 4.7
8505 puts n.instance_of?(Float) # true
8506 puts n.instance_of?(Numeric) # false
8507
8508 # ask an object whether it is an instance of class, one of the
8509 # superclasses of the object, or modules included in it
8510 puts n.kind_of?(Float) # true (the class)
8511 puts n.kind_of?(Numeric) # true (an ancestor class)
8512 puts n.kind_of?(Comparable) # true (a mixin module)
8513 puts n.kind_of?(String) # false
8514
8515 # ask an object whether it can respond to a particular method
8516 puts n.respond_to?('+') # true
8517 puts n.respond_to?('length') # false
8518
8519 # all methods an object can respond to
8520 'just a string'.methods.each { |m| puts m }
8521
8522
8523 # @@PLEAC@@_13.9
8524 # Actually any class in Ruby is inheritable
8525 class Person
8526 attr_accessor :age, :name
8527 def initialize
8528 @name
8529 @age
8530 end
8531 end
8532 #-----------------------------
8533 dude = Person.new
8534 dude.name = 'Jason'
8535 dude.age = 23
8536 printf "%s is age %d.\n", dude.name, dude.age
8537 #-----------------------------
8538 # Inheriting from Person
8539 class Employee < Person
8540 attr_accessor :salary
8541 end
8542 #-----------------------------
8543 empl = Employee.new
8544 empl.name = 'Jason'
8545 empl.age = 23
8546 empl.salary = 200
8547 printf "%s is age %d, the salary is %d.\n", empl.name, empl.age, empl.salary
8548 #-----------------------------
8549 # Any built-in class can be inherited the same way
8550 class WeirdString < String
8551 def initialize(obj)
8552 super obj
8553 end
8554 def +(anotherObj) # + method in this class is overridden
8555 # to return the sum of string lengths
8556 self.length + anotherObj.length # 'self' can be omitted
8557 end
8558 end
8559 #-----------------------------
8560 a = WeirdString.new('hello')
8561 b = WeirdString.new('bye')
8562
8563 puts a + b # the overridden +
8564 #=> 8
8565 puts a.length # method from the superclass, String
8566 #=> 5
8567
8568
8569 # @@PLEAC@@_13.11
8570 # In ruby you can override the method_missing method
8571 # to have a solution similar to perls AUTOLOAD.
8572 class Person
8573
8574 def initialize
8575 @ok_fields = %w(name age peers parent)
8576 end
8577
8578 def valid_attribute?(name)
8579 @ok_fields.include?(name)
8580 end
8581
8582 def method_missing(namesymbol, *params)
8583 name = namesymbol.to_s
8584 return if name =~ /^A-Z/
8585 if name.to_s[-1] == ('='[0]) # we have a setter
8586 isSetter = true
8587 name.sub!(/=$/, '')
8588 end
8589 if valid_attribute?(name)
8590 if isSetter
8591 instance_variable_set("@#{name}", *params)
8592 else
8593 instance_variable_get("@#{name}", *params)
8594 end
8595 else
8596 # if no annestor is responsible,
8597 # the Object class will throw a NoMethodError exception
8598 super(namesymbol, *params)
8599 end
8600 end
8601
8602 def new
8603 kid = Person.new
8604 kid.parent = self
8605 kid
8606 end
8607
8608 end
8609
8610 dad = Person.new
8611 dad.name = "Jason"
8612 dad.age = 23
8613 kid = dad.new
8614 kid.name = "Rachel"
8615 kid.age = 2
8616 puts "Kid's parent is #{kid.parent.name}"
8617 puts dad
8618 puts kid
8619
8620 class Employee < Person
8621 def initialize
8622 super
8623 @ok_fields.push("salary", "boss")
8624 end
8625 def ok_fields
8626 @ok_fields
8627 end
8628 end
8629
8630
8631 # @@PLEAC@@_13.13
8632 # The ruby garbage collector pretends to cope with circular structures.
8633 # You can test it with this code:
8634 class RingNode
8635 attr_accessor :next
8636 attr_accessor :prev
8637 attr_reader :name
8638
8639 def initialize(aName)
8640 @name = aName
8641 ObjectSpace.define_finalizer(self,
8642 self.class.method(:finalize).to_proc)
8643 end
8644
8645 def RingNode.finalize(id)
8646 puts "Node #{id} dying"
8647 end
8648
8649 def RingNode.show_all_objects
8650 ObjectSpace.each_object {|id|
8651 puts id.name if id.class == RingNode
8652 }
8653 end
8654 end
8655
8656 def create_test
8657 a = RingNode.new("Node A")
8658 b = RingNode.new("Node B")
8659 c = RingNode.new("Node C")
8660 a.next = b
8661 b.next = c
8662 c.next = a
8663 a.prev = c
8664 c.prev = b
8665 b.prev = a
8666
8667 a = nil
8668 b = nil
8669 c = nil
8670 end
8671
8672 create_test
8673 RingNode.show_all_objects
8674 ObjectSpace.garbage_collect
8675 puts "After garbage collection"
8676 RingNode.show_all_objects
8677
8678
8679 # @@PLEAC@@_13.14
8680 class String
8681 def <=>(other)
8682 self.casecmp other
8683 end
8684 end
8685
8686 # There is no way to directly overload the '""' (stringify)
8687 # operator in Ruby. However, by convention, classes which
8688 # can reasonably be converted to a String will define a
8689 # 'to_s' method as in the TimeNumber class defined below.
8690 # The 'puts' method will automatcally call an object's
8691 # 'to_s' method as is demonstrated below.
8692 # Furthermore, if a class defines a to_str method, an object of that
8693 # class can be used most any place where the interpreter is looking
8694 # for a String value.
8695
8696 #---------------------------------------
8697 # NOTE: Ruby has a builtin Time class which would usually be used
8698 # to manipulate time objects, the following is supplied for
8699 # educational purposes to demonstrate operator overloading.
8700 #
8701 class TimeNumber
8702 attr_accessor :hours,:minutes,:seconds
8703 def initialize( hours, minutes, seconds)
8704 @hours = hours
8705 @minutes = minutes
8706 @seconds = seconds
8707 end
8708
8709 def to_s
8710 return sprintf( "%d:%02d:%02d", @hours, @minutes, @seconds)
8711 end
8712
8713 def to_str
8714 to_s
8715 end
8716
8717 def +( other)
8718 seconds = @seconds + other.seconds
8719 minutes = @minutes + other.minutes
8720 hours = @hours + other.hours
8721 if seconds >= 60
8722 seconds %= 60
8723 minutes += 1
8724 end
8725 if minutes >= 60
8726 minutes %= 60
8727 hours += 1
8728 end
8729 return TimeNumber.new(hours, minutes, seconds)
8730 end
8731
8732 def -(other)
8733 raise NotImplementedError
8734 end
8735
8736 def *(other)
8737 raise NotImplementedError
8738 end
8739
8740 def /( other)
8741 raise NotImplementedError
8742 end
8743 end
8744
8745 t1 = TimeNumber.new(0, 58, 59)
8746 sec = TimeNumber.new(0, 0, 1)
8747 min = TimeNumber.new(0, 1, 0)
8748 puts t1 + sec + min + min
8749
8750 #-----------------------------
8751 # StrNum class example: Ruby's builtin String class already has the
8752 # capabilities outlined in StrNum Perl example, however the '*' operator
8753 # on Ruby's String class acts differently: It creates a string which
8754 # is the original string repeated N times.
8755 #
8756 # Using Ruby's String class as is in this example:
8757 x = "Red"; y = "Black"
8758 z = x+y
8759 r = z*3 # r is "RedBlackRedBlackRedBlack"
8760 puts "values are #{x}, #{y}, #{z}, and #{r}"
8761 print "#{x} is ", x < y ? "LT" : "GE", " #{y}\n"
8762 # prints:
8763 # values are Red, Black, RedBlack, and RedBlackRedBlackRedBlack
8764 # Red is GE Black
8765
8766 #-----------------------------
8767 class FixNum
8768 REGEX = /(\.\d*)/
8769 DEFAULT_PLACES = 0
8770 attr_accessor :value, :places
8771 def initialize(value, places = nil)
8772 @value = value
8773 if places
8774 @places = places
8775 else
8776 m = REGEX.match(value.to_s)
8777 if m
8778 @places = m[0].length - 1
8779 else
8780 @places = DEFAULT_PLACES
8781 end
8782 end
8783 end
8784
8785 def +(other)
8786 FixNum.new(@value + other.value, max(@places, other.places))
8787 end
8788
8789 def *(other)
8790 FixNum.new(@value * other.value, max(@places, other.places))
8791 end
8792
8793 def /(other)
8794 puts "Divide: #{@value.to_f/other.value.to_f}"
8795 result = FixNum.new(@value.to_f/other.value.to_f)
8796 result.places = max(result.places,other.places)
8797 result
8798 end
8799
8800 def to_s
8801 sprintf("STR%s: %.*f", self.class.to_s , @places, @value) #.
8802 end
8803
8804 def to_str
8805 to_s
8806 end
8807
8808 def to_i #convert to int
8809 @value.to_i
8810 end
8811
8812 def to_f #convert to float`
8813 @value.to_f
8814 end
8815
8816 private
8817 def max(a,b)
8818 a > b ? a : b
8819 end
8820 end
8821
8822 def demo()
8823 x = FixNum.new(40)
8824 y = FixNum.new(12, 0)
8825
8826 puts "sum of #{x} and #{y} is #{x+y}"
8827 puts "product of #{x} and #{y} is #{x*y}"
8828
8829 z = x/y
8830 puts "#{z} has #{z.places} places"
8831 unless z.places
8832 z.places = 2
8833 end
8834
8835 puts "div of #{x} by #{y} is #{z}"
8836 puts "square of that is #{z*z}"
8837 end
8838
8839 if __FILE__ == $0
8840 demo()
8841 end
8842
8843
8844 # @@PLEAC@@_14.1
8845 # There are dbm, sdbm, gdbm modules
8846 # and the bdb module for accessing the berkeley db
8847 # sdbm seem to be available on the most systems,
8848 # so we use it here
8849 #
8850 require "sdbm"
8851 SDBM.open("filename", 0666) { |dbobj|
8852 # raises exception if open error
8853
8854 # the returned sdbm-dbobj has most of the methods of a hash
8855 v = dbobj["key"]
8856 dbobj["key"] = "newvalue"
8857 if dbobj.has_key?("key")
8858 # ...
8859 end
8860 dbobj.delete("key2")
8861 }
8862 # database is open only inside the block.
8863
8864 # It is also possible to use a open .. close pair:
8865 dbobj = SDBM.open("filename", 0666)
8866 #.. do something with dbobj
8867 dbobj.close
8868
8869 #!/usr/bin/ruby -w
8870 # userstats - generate statistics on who is logged in
8871 # call with usernames as argument to display the totals
8872 # for the given usernames, call with "ALL" to display all users
8873
8874 require "sdbm"
8875 filename = '/tmp/userstats.db'
8876 SDBM.open(filename, 0666) { |dbobj|
8877 if ARGV.length > 0
8878 if ARGV[0] == "ALL"
8879 # ARGV is constant, so we need the variable userlist
8880 userlist = dbobj.keys().sort()
8881 else
8882 userlist = ARGV
8883 end
8884 userlist.each { |user|
8885 print "#{user}\t#{dbobj[user]}\n"
8886 }
8887 else
8888 who = `who`
8889 who.split("\n").each { |line|
8890 md = /^(\S+)/.match(line)
8891 raise "Bad line from who: #{line}" unless md
8892 # sdbm stores only strings, so "+=" doesn't work,
8893 # we need to convert them expicitly back to integer.
8894 if dbobj.has_key?(md[0])
8895 dbobj[md[0]] = dbobj[md[0]].to_i + 1
8896 else
8897 dbobj[md[0]] = "1"
8898 end
8899 }
8900 end
8901 }
8902
8903
8904 # @@PLEAC@@_14.2
8905 # using open and clear
8906 dbobj = SDBM.open("filename", 0666)
8907 dbobj.clear()
8908 dbobj.close()
8909 # deleting file and recreating it
8910 # the filenames depend on the flavor of dbm you use,
8911 # for example sdbm has two files named filename.pag and filename.dir,
8912 # so you need to delete both files
8913 begin
8914 File.delete("filename")
8915 # raises Exception if not exist
8916 dbobj = SDBM.open("filename", 0666)
8917 rescue
8918 # add error handling here
8919 end
8920
8921
8922 # @@PLEAC@@_14.3
8923 # sdbm2gdbm: converts sdbm database to a gdbm database
8924 require "sdbm"
8925 require "gdbm"
8926
8927 unless ARGV.length == 2
8928 fail "usage: sdbm2gdbm infile outfile"
8929 end
8930 infile = ARGV[0]
8931 outfile = ARGV[1]
8932
8933 sdb = SDBM.open(infile)
8934 gdb = GDBM.open(outfile, 0666)
8935 sdb.each { |key, val|
8936 gdb[key] = val
8937 }
8938 gdb.close
8939 sdb.close
8940
8941
8942 # @@PLEAC@@_14.4
8943 #!/usr/bin/ruby -w
8944 # dbmmerge: merges two dbm databases
8945 require "sdbm"
8946
8947 unless ARGV.length == 3
8948 fail "usage: dbmmerge indb1 indb2 outdb"
8949 end
8950 infile1 = ARGV[0]
8951 infile2 = ARGV[0]
8952 outfile = ARGV[2]
8953
8954 in1 = SDBM.open(infile1, nil)
8955 in2 = SDBM.open(infile2, nil)
8956 outdb = SDBM.open(outfile, 0666)
8957
8958 [in1, in2].each { |indb|
8959 indb.each { |key, val|
8960 if outdb.has_key?(key)
8961 # decide which value to set.
8962 # set outdb[key] if necessary
8963 else
8964 outdb[key] = val
8965 end
8966 }
8967 }
8968 in1.close
8969 in2.close
8970 outdb.close
8971
8972
8973 # @@PLEAC@@_14.7
8974 # we write a tie method that extends the Array class.
8975 # It reads the file into the memory, executes the code block
8976 # in which you can manipulate the array as needed, and writes
8977 # the array back to the file after the end of the block execution
8978 class Array
8979 def tie(filename, flags)
8980 File.open(filename, flags) { |f|
8981 f.each_line { |line|
8982 self.push(line.chomp)
8983 }
8984 yield
8985 f.rewind
8986 each { |line|
8987 if line
8988 f.puts(line)
8989 else
8990 f.puts ""
8991 end
8992 }
8993 }
8994 end
8995 end
8996
8997 array = Array.new
8998 array.tie("/tmp/textfile.txt", File::RDWR|File::CREAT) {
8999 array[4] = "a new line 4"
9000 }
9001
9002 # The tied array can be manipulated like a normal array,
9003 # so there is no need for a special API, and the recno_demo program
9004 # to demonstrate is API is useless
9005
9006
9007 # tied array demo: show how to use array with a tied file
9008 filename = "db_file.txt"
9009 lines = Array.new
9010 File.unlink(filename) if File.exists?(filename)
9011 lines.tie(filename, File::RDWR | File::CREAT) {
9012 # first create a textfile to play with
9013 lines[0] = "zero"
9014 lines[1] = "one"
9015 lines[2] = "two"
9016 lines[3] = "three"
9017 lines[4] = "four"
9018
9019 # print the records in order.
9020 # Opposed to perl, the tied array behaves exactly as a normal array
9021 puts "\nOriginal"
9022 for i in 0..(lines.length-1)
9023 puts "#{i}: #{lines[i]}"
9024 end
9025
9026 #use push and pop
9027 a = lines.pop
9028 lines.push("last")
9029 puts("The last line was [#{a}]")
9030
9031 #use shift and unshift
9032 a = lines.shift
9033 lines.unshift("first")
9034 puts("The first line was [#{a}]")
9035
9036 # add record after record 2
9037 i = 2
9038 lines.insert(i + 1, "Newbie")
9039
9040 # add record before record one
9041 i = 1
9042 lines.insert(i, "New One")
9043
9044 # delete record 3
9045 lines.delete_at(3)
9046
9047 #now print the records in reverse order
9048 puts "\nReverse"
9049 (lines.length - 1).downto(0){ |i|
9050 puts "#{i}: #{lines[i]}"
9051 }
9052
9053 }
9054
9055
9056 # @@PLEAC@@_14.8
9057 # example to store complex data in a database
9058 # uses marshall from the standard library
9059 require "sdbm"
9060 db = SDBM.open("pleac14-8-database", 0666)
9061
9062 # convert the Objects into strings and back by using the Marshal module.
9063 # Most normal objects can be converted out of the box,
9064 # but not special things like procedure objects,
9065 # IO instance variables, singleton objects
9066
9067 db["Tom Christiansen"] = Marshal.dump(["book author", "[email protected]"])
9068 db["Tom Boutell"] = Marshal.dump(["shareware author",
9069 "[email protected]"])
9070
9071 name1 = "Tom Christiansen"
9072 name2 = "Tom Boutell"
9073
9074 tom1 = Marshal.load(db[name1])
9075 tom2 = Marshal.load(db[name2])
9076
9077 puts "Two Toming: #{tom1} #{tom2}"
9078
9079 if tom1[0] == tom2[0] && tom1[1] == tom2[1]
9080 puts "You're having runtime fun with one Tom made two."
9081 else
9082 puts "No two Toms are ever alike"
9083 end
9084
9085 # To change parts of an entry, get the whole entry, change the parts,
9086 # and save the whole entry back
9087 entry = Marshal.load(db["Tom Boutell"])
9088 entry[0] = "Poet Programmer"
9089 db["Tom Boutell"] = Marshal.dump(entry)
9090 db.close
9091
9092
9093 # @@PLEAC@@_14.9
9094 # example to make data persistent
9095 # uses Marshal from the standard lib
9096 # Stores the data in a simple file,
9097 # see 14.8 on how to store it in a dbm file
9098
9099 # The BEGIN block is executed before the rest of the script
9100 # we use global variables here because local variables
9101 # will go out of scope and are not accessible from the main script
9102
9103 BEGIN {
9104 $persistent_store = "persitence.dat"
9105 begin
9106 File.open($persistent_store) do |f|
9107 $stringvariable1 = Marshal.load(f)
9108 $arrayvariable2 = Marshal.load(f)
9109 end
9110 rescue
9111 puts "Can not open #{$persistent_store}"
9112 # Initialisation if this script runs the first time
9113 $stringvariable1 = ""
9114 $arrayvariable2 = []
9115 end
9116 }
9117
9118 END {
9119 File.open($persistent_store, "w+") do |f|
9120 Marshal.dump($stringvariable1, f)
9121 Marshal.dump($arrayvariable2, f)
9122 end
9123 }
9124
9125 # simple test program
9126 puts $stringvariable1
9127 puts $arrayvariable2
9128 $stringvariable1 = "Hello World"
9129 $arrayvariable2.push(5)
9130 puts $stringvariable1
9131 puts $arrayvariable2
9132
9133
9134 # @@PLEAC@@_14.10
9135 #!/usr/bin/ruby -w
9136 # Ruby has a dbi module with an architecture similar
9137 # to the Perl dbi module: the dbi module provides an unified
9138 # interface and uses specialized drivers for each dbms vendor
9139 #
9140 begin
9141 DBI.connect("DBI:driver:driverspecific", "username", "auth") {
9142 |dbh|
9143
9144 dbh.do(SQL1)
9145
9146 dbh.prepare(SQL2){ |sth|
9147 sth.execute
9148 sth.fetch {|row|
9149 # ...
9150 }
9151 } # end of block finishes the statement handle
9152 } # end of block closes the database connection
9153 rescue DBI::DatabaseError => e
9154 puts "dbi error occurred"
9155 puts "Error code: #{e.err}"
9156 puts "Error message: #{e.errstr}"
9157 end
9158
9159 #!/usr/bin/ruby -w
9160 # dbusers - example for mysql which creates a table,
9161 # fills it with values, retrieves the values back,
9162 # and finally destroys the table.
9163
9164 require "dbi"
9165
9166 # replacement for the User::pwnt module
9167 def getpwent
9168 result = []
9169 File.open("/etc/passwd") {|file|
9170 file.each_line {|line|
9171 next if line.match(/^#/)
9172 cols = line.split(":")
9173 result.push([cols[2], cols[0]])
9174 }
9175 }
9176 result
9177 end
9178
9179 begin
9180 DBI.connect("DBI:Mysql:pleacdatabase", "pleac", "pleacpassword") {
9181 |conn|
9182
9183 conn.do("CREATE TABLE users (uid INT, login CHAR(8))")
9184
9185 users = getpwent
9186
9187 conn.prepare("INSERT INTO users VALUES (?,?)") {|sth|
9188 users.each {|entry|
9189 sth.execute(entry[0], entry[1])
9190 }
9191 }
9192
9193 conn.execute("SELECT uid, login FROM users WHERE uid < 50") {|sth|
9194 sth.fetch {|row|
9195 puts row.collect {|col|
9196 if col.nil?
9197 "(null)"
9198 else
9199 col
9200 end
9201 }.join(", ")
9202 }
9203 }
9204
9205 conn.do("DROP TABLE users")
9206 }
9207 rescue DBI::DatabaseError => e
9208 puts "dbi error occurred"
9209 puts "Error code: #{e.err}"
9210 puts "Error message: #{e.errstr}"
9211 end
9212
9213
9214 # @@PLEAC@@_15.1
9215 # This test program demonstrates parsing program arguments.
9216 # It uses the optparse library, which is included with ruby 1.8
9217 # It handles classic unix style and gnu style options
9218 require 'optparse'
9219
9220 @debugmode = false
9221 @verbose = false
9222
9223 ARGV.options do |opts|
9224 opts.banner = "Usage: ruby #{$0} [OPTIONS] INPUTFILES"
9225
9226 opts.on("-h", "--help", "show this message") {
9227 puts opts
9228 exit
9229 }
9230 # The OptionParser#on method is called with a specification of short
9231 # options, of long options, a data type spezification and user help
9232 # messages for this option.
9233 # The method analyses the given parameter and decides what it is,
9234 # so you can leave out the long option if you don't need it
9235 opts.on("-v", "--[no-]verbose=[FLAG]", TrueClass, "run verbosly") {
9236 |@verbose| # sets @verbose to true or false
9237 }
9238 opts.on("-D", "--DEBUG", TrueClass, "turns on debug mode" ){
9239 |@debugmode| # sets @debugmode to true
9240 }
9241 opts.on("-c", "--count=NUMBER", Integer, "how many times we do it" ){
9242 |@count| # sets @count to given integer
9243 }
9244 opts.on("-o", "--output=FILE", String, "file to write output to"){
9245 |@outputfile| # sets @outputfile to given string
9246 }
9247 opts.parse!
9248 end
9249
9250 # example to use the options in the main program
9251 puts "Verbose is on" if @verbose
9252 puts "Debugmode is on" if @debugmode
9253 puts "Outfile is #{@outputfile}" if defined? @outputfile
9254 puts "Count is #{@count}" if defined? @count
9255 ARGV.each { |param|
9256 puts "Got parameter #{param}"
9257 }
9258
9259
9260 # @@PLEAC@@_15.4
9261 buf = "\0" * 8
9262 $stdout.ioctl(0x5413, buf)
9263 ws_row, ws_col, ws_xpixel, ws_ypixel = buf.unpack("S4")
9264
9265 raise "You must have at least 20 characters" unless ws_col >= 20
9266 max = 0
9267 values = (1..5).collect { rand(20) } # generate an array[5] of rand values
9268 for i in values
9269 max = i if max < i
9270 end
9271 ratio = Float(ws_col-12)/max # chars per unit
9272 for i in values
9273 printf "%8.1f %s\n", i, "*" * (ratio*i)
9274 end
9275
9276 # gives, for example:
9277 # 15.0 *******************************
9278 # 10.0 *********************
9279 # 5.0 **********
9280 # 14.0 *****************************
9281 # 18.0 **************************************
9282
9283
9284 # @@PLEAC@@_16.1
9285 output = `program args` # collect output into one multiline string
9286 output = `program args`.split # collect output into array, one line per
9287 element
9288
9289 readme = IO.popen("ls")
9290 output = ""
9291 while readme.gets do
9292 output += $_
9293 end
9294 readme.close
9295
9296 `fsck -y /dev/rsd1a` # BAD AND SCARY in Perl because it's managed by the shell
9297 # I donna in Ruby ...
9298
9299 # so the "clean and secure" version
9300 readme, writeme = IO.pipe
9301 pid = fork {
9302 # child
9303 $stdout = writeme
9304 readme.close
9305 exec('find', '..')
9306 }
9307 # parent
9308 Process.waitpid(pid, 0)
9309 writeme.close
9310 while readme.gets do
9311 # do something with $_
9312 end
9313
9314
9315 # @@PLEAC@@_16.2
9316 status = system("xemacs #{myfile}")
9317
9318 status = system("xemacs", myfile)
9319
9320 system("cmd1 args | cmd2 | cmd3 >outfile")
9321 system("cmd args <infile >outfile 2>errfile")
9322
9323 # stop if the command fails
9324 raise "$program exited funny: #{$?}" unless system("cmd", "args1", "args2")
9325
9326 # get the value of the signal sent to the child
9327 # even if it is a SIGINT or SIGQUIT
9328 system(arglist)
9329 raise "program killed by signal #{$?}" if ($? & 127) != 0
9330
9331 pid = fork {
9332 trap("SIGINT", "IGNORE")
9333 exec("sleep", "10")
9334 }
9335 trap ("SIGINT") {
9336 puts "Tsk tsk, no process interruptus"
9337 }
9338 Process.waitpid(pid, 0)
9339
9340 # Ruby doesn't permit to lie to the program called by a 'system'.
9341 # (ie specify what return argv[0] in C, $0 in Perl/Ruby ...)
9342 # A (dirty) way is to create a link (under Unix), run this link and
9343 # erase it. Somebody has a best idea ?
9344
9345
9346 # @@PLEAC@@_16.3
9347 exec("archive *.data")
9348
9349 exec("archive", "accounting.data")
9350
9351 exec("archive accounting.data")
9352
9353
9354 # @@PLEAC@@_16.4
9355 # read the output of a program
9356 IO.popen("ls") {|readme|
9357 while readme.gets do
9358 # ...
9359 end
9360 }
9361 # or
9362 readme = IO.popen("ls")
9363 while readme.gets do
9364 # ...
9365 end
9366 readme.close
9367
9368 # "write" in a program
9369 IO.popen("cmd args","w") {|pipe|
9370 pipe.puts("data")
9371 pipe.puts("foo")
9372 }
9373
9374 # close wait for the end of the process
9375 read = IO.popen("sleep 10000") # child goes to sleep
9376 read.close # and the parent goes to lala land
9377
9378 writeme = IO.popen("cmd args", "w")
9379 writeme.puts "hello" # program will get hello\n on STDIN
9380 writeme.close # program will get EOF on STDIN
9381
9382 # send in a pager (eg less) all output
9383 $stdout = IO.popen("/usr/bin/less","w")
9384 print "huge string\n" * 10000
9385
9386
9387 # @@PLEAC@@_16.5
9388 #-----------------------------
9389 def head(lines = 20)
9390 pid = open("|-","w")
9391 if pid == nil
9392 return
9393 else
9394 while gets() do
9395 pid.print
9396 lines -= 1
9397 break if lines == 0
9398 end
9399 end
9400 exit
9401 end
9402
9403 head(100)
9404 while gets() do
9405 print
9406 end
9407 #-----------------------------
9408 1: > Welcome to Linux, version 2.0.33 on a i686
9409
9410 2: >
9411
9412 3: > "The software required `Windows 95 or better',
9413
9414 4: > so I installed Linux."
9415 #-----------------------------
9416 > 1: Welcome to Linux, Kernel version 2.0.33 on a i686
9417
9418 > 2:
9419
9420 > 3: "The software required `Windows 95 or better',
9421
9422 > 4: so I installed Linux."
9423 #-----------------------------
9424 #!/usr/bin/ruby
9425 # qnumcat - demo additive output filters
9426
9427 def number()
9428 pid = open("|-","w")
9429 if pid == nil
9430 return
9431 else
9432 while gets() do pid.printf("%d: %s", $., $_); end
9433 end
9434 exit
9435 end
9436
9437 def quote()
9438 pid = open("|-","w")
9439 if pid == nil
9440 return
9441 else
9442 while gets() do pid.print "> #{$_}" end
9443 end
9444 exit
9445 end
9446
9447 number()
9448 quote()
9449
9450 while gets() do
9451 print
9452 end
9453 $stdout.close
9454 exit
9455
9456
9457 # @@PLEAC@@_16.6
9458 ARGV.map! { |arg|
9459 arg =~ /\.(gz|Z)$/ ? "|gzip -dc #{arg}" : arg
9460 }
9461 for file in ARGV
9462 fh = open(file)
9463 while fh.gets() do
9464 # .......
9465 end
9466 end
9467 #-----------------------------
9468 ARGV.map! { |arg|
9469 arg =~ %r#^\w+://# ? "|GET #{arg}" : arg #
9470 }
9471 for file in ARGV
9472 fh = open(file)
9473 while fh.gets() do
9474 # .......
9475 end
9476 end
9477 #-----------------------------
9478 pwdinfo = (`domainname` =~ /^(\(none\))?$/) ? '/etc/passwd' : '|ypcat passwd';
9479 pwd = open(pwdinfo);
9480 #-----------------------------
9481 puts "File, please? ";
9482 file = gets().chomp();
9483 fh = open(file);
9484
9485
9486 # @@PLEAC@@_16.7
9487 output = `cmd 2>&1` # with backticks
9488 # or
9489 ph = open("|cmd 2>&1") # with an open pipe
9490 while ph.gets() { } # plus a read
9491 #-----------------------------
9492 output = `cmd 2>/dev/null` # with backticks
9493 # or
9494 ph = open("|cmd 2>/dev/null") # with an open pipe
9495 while ph.gets() { } # plus a read
9496 #-----------------------------
9497 output = `cmd 2>&1 1>/dev/null` # with backticks
9498 # or
9499 ph = open("|cmd 2>&1 1>/dev/null") # with an open pipe
9500 while ph.gets() { } # plus a read
9501 #-----------------------------
9502 output = `cmd 3>&1 1>&2 2>&3 3>&-` # with backticks
9503 # or
9504 ph = open("|cmd 3>&1 1>&2 2>&3 3>&-") # with an open pipe
9505 while ph.gets() { } # plus a read
9506 #-----------------------------
9507 system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr")
9508 #-----------------------------
9509 output = `cmd 3>&1 1>&2 2>&3 3>&-`
9510 #-----------------------------
9511 fd3 = fd1
9512 fd1 = fd2
9513 fd2 = fd3
9514 fd3 = undef
9515 #-----------------------------
9516 system("prog args 1>tmpfile 2>&1")
9517 system("prog args 2>&1 1>tmpfile")
9518 #-----------------------------
9519 # system ("prog args 1>tmpfile 2>&1")
9520 fd1 = "tmpfile" # change stdout destination first
9521 fd2 = fd1 # now point stderr there, too
9522 #-----------------------------
9523 # system("prog args 2>&1 1>tmpfile")
9524 fd2 = fd1 # stderr same destination as stdout
9525 fd1 = "tmpfile" # but change stdout destination
9526 #-----------------------------
9527 # It is often better not to rely on the shell,
9528 # because of portability, possible security problems
9529 # and bigger resource usage. So, it is often better to use the open3 library.
9530 # See below for an example.
9531 # opening stdin, stdout, stderr
9532 require "open3"
9533 stdin, stdout, stderr = Open3.popen('cmd')
9534
9535
9536 # @@PLEAC@@_16.8
9537 #-----------------------------
9538 # Contrary to perl, we don't need to use a module in Ruby
9539 fh = Kernel.open("|" + program, "w+")
9540 fh.puts "here's your input\n"
9541 output = fh.gets()
9542 fh.close()
9543 #-----------------------------
9544 Kernel.open("|program"),"w+") # RIGHT !
9545 #-----------------------------
9546 # Ruby has already object methods for I/O handles
9547 #-----------------------------
9548 begin
9549 fh = Kernel.open("|" + program_and_options, "w+")
9550 rescue
9551 if ($@ ~= /^open/)
9552 $stderr.puts "open failed : #{$!} \n #{$@} \n"
9553 break
9554 end
9555 raise # reraise unforseen exception
9556 end
9557
9558
9559 # @@PLEAC@@_16.13
9560 #% kill -l
9561 #HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE
9562 #ALRM TERM CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM
9563 #PROF WINCH POLL PWR
9564 #-----------------------------
9565 #% ruby -e 'puts Signal.list.keys.join(" ")'
9566 #PWR USR1 BUS USR2 TERM SEGV KILL POLL STOP SYS TRAP IOT HUP INT #
9567 #WINCH XCPU TTIN CLD TSTP FPE IO TTOU PROF CHLD CONT PIPE ABRT
9568 #VTALRM QUIT ILL XFSZ URG ALRM
9569 #-----------------------------
9570 # After that, the perl script create an hash equivalent to Signal.list,
9571 # and an array. The array can be obtained by :
9572 signame = []
9573 Signal.list.each { |name, i| signame[i] = name }
9574
9575
9576 # @@PLEAC@@_16.14
9577 Process.kill(9, pid) # send $pid a signal 9
9578 Process.kill(-1, Process.getpgrp()) # send whole job a signal 1
9579 Process.kill("USR1", $$) # send myself a SIGUSR1
9580 Process.kill("HUP", pid1, pid2, pid3) # send a SIGHUP to processes in @pids
9581 #-----------------------------
9582 begin
9583 Process.kill(0, minion)
9584 puts "#{minion} is alive!"
9585 rescue Errno::EPERM # changed uid
9586 puts "#{minion} has escaped my control!";
9587 rescue Errno::ESRCH
9588 puts "#{minion} is deceased."; # or zombied
9589 rescue
9590 puts "Odd; I couldn't check the status of #{minion} : #{$!}"
9591 end
9592
9593
9594 # @@PLEAC@@_16.15
9595 Kernel.trap("QUIT", got_sig_quit) # got_sig_quit = Proc.new { puts "Quit\n" }
9596 trap("PIPE", "got_sig_quit") # def got_sig_pipe ...
9597 trap("INT") { ouch++ } # increment ouch for every SIGINT
9598 #-----------------------------
9599 trap("INT", "IGNORE") # ignore the signal INT
9600 #-----------------------------
9601 trap("STOP", "DEFAULT") # restore default STOP signal handling
9602
9603
9604 # @@PLEAC@@_16.16
9605 # the signal handler
9606 def ding
9607 trap("INT", "ding")
9608 puts "\aEnter your name!"
9609 end
9610
9611 # prompt for name, overriding SIGINT
9612 def get_name
9613 save = trap("INT", "ding")
9614
9615 puts "Kindly Stranger, please enter your name: "
9616 name = gets().chomp()
9617 trap("INT", save)
9618 name
9619 end
9620
9621
9622 # @@PLEAC@@_16.21
9623 # implemented thanks to http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/1760
9624 require 'timeout'
9625
9626 # we'll do something vastly more useful than cookbook to demonstrate timeouts
9627 begin
9628 timeout(5) {
9629 waitsec = rand(10)
9630 puts "Let's see if a sleep of #{waitsec} seconds is longer than 5 seconds..."
9631 system("sleep #{waitsec}")
9632 }
9633 puts "Timeout didn't occur"
9634 rescue Timeout::Error
9635 puts "Timed out!"
9636 end
9637
9638
9639 # @@PLEAC@@_17.1
9640 # A basic TCP client connection
9641 require 'socket'
9642 begin
9643 t = TCPSocket.new('www.ruby-lang.org', 'www')
9644 rescue
9645 puts "error: #{$!}"
9646 else
9647 # ... do something with the socket
9648 t.print "GET / HTTP/1.0\n\n"
9649 answer = t.gets(nil)
9650 # and terminate the connection when we're done
9651 t.close
9652 end
9653
9654 # Using the evil low level socket API
9655 require 'socket'
9656 # create a socket
9657 s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
9658 # build the address of the remote machine
9659 sockaddr_server = [Socket::AF_INET, 80,
9660 Socket.gethostbyname('www.ruby-lang.org')[3],
9661 0, 0].pack("snA4NN")
9662 # connect
9663 begin
9664 s.connect(sockaddr_server)
9665 rescue
9666 puts "error: #{$!}"
9667 else
9668 # ... do something with the socket
9669 s.print "GET / HTTP/1.0\n\n"
9670 # and terminate the connection when we're done
9671 s.close
9672 end
9673
9674 # TCP connection with management of error (DNS)
9675 require 'socket'
9676 begin
9677 client = TCPSocket.new('does not exists', 'www')
9678 rescue
9679 puts "error: #{$!}"
9680 end
9681
9682 # TCP connection with a time out
9683 require 'socket'
9684 require 'timeout'
9685 begin
9686 timeout(1) do #the server has one second to answer
9687 client = TCPSocket.new('www.host.com', 'www')
9688 end
9689 rescue
9690 puts "error: #{$!}"
9691 end
9692
9693
9694 # @@PLEAC@@_17.12
9695 require 'socket'
9696
9697 class Preforker
9698 attr_reader (:child_count)
9699
9700 def initialize(prefork, max_clients_per_child, port, client_handler)
9701 @prefork = prefork
9702 @max_clients_per_child = max_clients_per_child
9703 @port = port
9704 @child_count = 0
9705
9706 @reaper = proc {
9707 trap('CHLD', @reaper)
9708 pid = Process.wait
9709 @child_count -= 1
9710 }
9711
9712 @huntsman = proc {
9713 trap('CHLD', 'IGNORE')
9714 trap('INT', 'IGNORE')
9715 Process.kill('INT', 0)
9716 exit
9717 }
9718
9719 @client_handler=client_handler
9720 end
9721
9722 def child_handler
9723 trap('INT', 'EXIT')
9724 @client_handler.setUp
9725 # wish: sigprocmask UNblock SIGINT
9726 @max_clients_per_child.times {
9727 client = @server.accept or break
9728 @client_handler.handle_request(client)
9729 client.close
9730 }
9731 @client_handler.tearDown
9732 end
9733
9734 def make_new_child
9735 # wish: sigprocmask block SIGINT
9736 @child_count += 1
9737 pid = fork do
9738 child_handler
9739 end
9740 # wish: sigprocmask UNblock SIGINT
9741 end
9742
9743 def run
9744 @server = TCPserver.open(@port)
9745 trap('CHLD', @reaper)
9746 trap('INT', @huntsman)
9747 loop {
9748 (@prefork - @child_count).times { |i|
9749 make_new_child
9750 }
9751 sleep .1
9752 }
9753 end
9754 end
9755
9756 #-----------------------------
9757 #!/usr/bin/ruby
9758
9759 require 'Preforker'
9760
9761 class ClientHandler
9762 def setUp
9763 end
9764
9765 def tearDown
9766 end
9767
9768 def handle_request(client)
9769 # do stuff
9770 end
9771 end
9772
9773 server = Preforker.new(1, 100, 3102, ClientHandler.new)
9774 server.run
9775
9776
9777 # @@PLEAC@@_18.2
9778 require 'net/ftp'
9779
9780 begin
9781 ftp = Net::FTP::new("ftp.host.com")
9782 ftp.login(username,password)
9783 ftp.chdir(directory)
9784 ftp.get(filename)
9785 ftp.put(filename)
9786 rescue Net::FTPError
9787 $stderr.print "FTP failed: " + $!
9788 ensure
9789 ftp.close() if ftp
9790 end
9791
9792 # A better solution for a local use could be :
9793 Net::FTP::new("ftp.host.com") do |ftp|
9794 ftp.login(username,password)
9795 ftp.chdir(directory)
9796 ftp.get(filename)
9797 ftp.put(filename)
9798 end
9799
9800 # If you have only one file to get, there is a simple solution :
9801 require 'open-uri'
9802 open("ftp://www.ruby-lang.org/path/filename") do |fh|
9803 # read from filehandle fh
9804 end
9805 #--------------------------------------------
9806 # to wait a defined time for the connection,
9807 # use the timeout module
9808 require 'timeout'
9809 begin
9810 timeout(30){
9811 ftp = Net::FTP::new("ftp.host.com")
9812 ftp.debug_mode = true
9813 }
9814 rescue Net::FTPError
9815 $stderr.puts "Couldn't connect."
9816 rescue Timeout::Error
9817 $stderr.puts "Timeout while connecting to server."
9818 end
9819
9820 begin
9821 ftp.login()
9822 rescue Net::FTPError
9823 $stderr.print "Couldn't authentificate.\n"
9824 end
9825
9826 begin
9827 ftp.login(username)
9828 rescue Net::FTPError
9829 $stderr.print "Still couldn't authenticate.\n"
9830 end
9831
9832 begin
9833 ftp.login(username, password)
9834 rescue Net::FTPError
9835 $stderr.print "Couldn't authenticate, even with explicit
9836 username and password.\n"
9837 end
9838
9839 begin
9840 ftp.login(username, password, account)
9841 rescue Net::FTPError
9842 $stderr.print "No dice. It hates me.\n"
9843 end
9844 #-----------------------------
9845 ftp.put(localfile, remotefile)
9846 #-----------------------------
9847 # Sending data from STDIN is not directly supported
9848 # by the ftp library module. A possible way to do it is to use the
9849 # storlines method directly to send raw commands to the ftp server.
9850 #-----------------------------
9851 ftp.get(remotefile, localfile)
9852 #-----------------------------
9853 ftp.get(remotefile) { |data| puts data }
9854 #-----------------------------
9855 ftp.chdir("/pub/ruby")
9856 print "I'm in the directory ", ftp.pwd(), "\n"
9857 #-----------------------------
9858 ftp.mkdir("/pub/ruby/new_dir")
9859 #-----------------------------
9860 lines = ftp.ls("/pub/ruby/")
9861 # => ["drwxr-xr-x 2 matz users 4096 July 17 1998 1.0", ... ]
9862
9863 latest = ftp.dir("/pub/ruby/*.tgz").sort.last
9864
9865 ftp.nlst("/pub/ruby")
9866 # => ["/pub/ruby/1.0", ... ]
9867 #-----------------------------
9868 ftp.quit()
9869
9870
9871 # @@PLEAC@@_18.6
9872 require 'net/telnet'
9873 t = Net::Telnet::new( "Timeout" => 10,
9874 "Prompt" => /%/,
9875 "Host" => host )
9876 t.login(username, password)
9877 files = t.cmd("ls")
9878 t.print("top")
9879 process_string = t.waitfor(/\d+ processes/)
9880 t.close
9881 #-----------------------------
9882 /[$%#>] \z/n
9883 #-----------------------------
9884 # In case of an error, the telnet module throws an exception.
9885 # For control of the behavior in case of an error,
9886 # you just need to catch the exceptions and do your custom
9887 # error handling.
9888 #-----------------------------
9889 begin
9890 telnet.login(username, password)
9891 rescue TimeoutError
9892 fail "Login failed !\n"
9893 end
9894 #-----------------------------
9895 telnet.waitfor('/--more--/')
9896 #-----------------------------
9897 telnet.waitfor(String => 'greasy smoke', Timeout => 30)
9898
9899
9900 # @@PLEAC@@_18.7
9901 require 'ping'
9902
9903 puts "#{host} is alive.\n" if Ping.pingecho(host);
9904 #-----------------------------
9905 # the ping module only use TCP ping, not ICMP even if we are root
9906 if Ping.pingecho("kingkong.com")
9907 puts "The giant ape lives!\n";
9908 else
9909 puts "All hail mighty Gamera, friend of children!\n";
9910 end
9911
9912
9913 # @@PLEAC@@_19.1
9914 #!/usr/local/bin/ruby -w
9915 # hiweb - load CGI class to decode information given by web server
9916
9917 require 'cgi'
9918
9919 cgi = CGI.new('html3')
9920
9921 # get a parameter from a form
9922 value = cgi.params['PARAM_NAME'][0]
9923
9924 # output a document
9925 cgi.out {
9926 cgi.html {
9927 cgi.head { cgi.title { "Howdy there!" } } +
9928 cgi.body { cgi.p { "You typed: " + cgi.tt {
9929 CGI.escapeHTML(value) } } }
9930 }
9931 }
9932
9933 require 'cgi'
9934 cgi = CGI.new
9935 who = cgi.param["Name"][0] # first param in list
9936 phone = cgi.param["Number"][0]
9937 picks = cgi.param["Choices"] # complete list
9938
9939 print cgi.header( 'type' => 'text/plain',
9940 'expires' => Time.now + (3 * 24 * 60 * 60) )
9941
9942
9943 # @@PLEAC@@_19.3
9944 #!/usr/local/bin/ruby -w
9945 # webwhoami - show web user's id
9946 require 'etc'
9947 print "Content-Type: text/plain\n\n"
9948 print "Running as " + Etc.getpwuid.name + "\n"
9949
9950 # % ruby -wc cgi-script # just check syntax
9951
9952 # % ruby -w cgi-script # params from stdin
9953 # (offline mode: enter name=value pairs on standard input)
9954 # name=joe
9955 # number=10
9956 # ^D
9957
9958 # % ruby -w cgi-script name=joe number=10 # run with mock form input
9959 # % ruby -d cgi-script name=joe number=10 # ditto, under the debugger
9960
9961 # POST method script in csh
9962 # % (setenv HTTP_METHOD POST; ruby -w cgi-script name=joe number=10)
9963 # POST method script in sh
9964 # % HTTP_METHOD=POST perl -w cgi-script name=joe number=10
9965
9966
9967 # @@PLEAC@@_19.4
9968 # ruby has several security levels, the level "1" is similar to perls taint mode.
9969 # It can be switched on by providing the -T command line parameter
9970 # or by setting $SAFE to 1. Setting $SAFE to 2,3 or 4 restricts possible
9971 # harmful operations further.
9972
9973 #!/usr/bin/ruby -T
9974 $SAFE = 1
9975 File.open(ARGV[0], "w")
9976 # ruby warns with:
9977 # taint1.rb:2:in `initialize': Insecure operation - initialize (SecurityError)
9978
9979 $SAFE = 1
9980 file = ARGV[0]
9981 unless /^([\w.-]+)$/.match(file)
9982 raise "filename #{file} has invalid characters"
9983 end
9984 file = $1
9985 # In ruby, even the back reference from a regular expression stays tainted.
9986 # you need to explicitly untaint the variable:
9987 file.untaint
9988 File.open(file, "w")
9989
9990 # Race condition exists like in perl:
9991 unless File.exists(filename) # Wrong because of race condition
9992 File.open(filename, "w")
9993 end
9994
9995
9996
9997 # @@PLEAC@@_19.10
9998 preference_value = cgi.cookies["preference name"][0]
9999
10000 packed_cookie = CGI::Cookie.new("name" => "preference name",
10001 "value" => "whatever you'd like",
10002 "expires" => Time.local(Time.now.year + 2,
10003 Time.now.mon, Time.now.day, Time.now.hour, Time.now.min, Time.now.sec) )
10004
10005 cgi.header("cookie" => [packed_cookie])
10006
10007 #!/usr/local/bin/ruby -w
10008 # ic_cookies - sample CGI script that uses a cookie
10009 require 'cgi'
10010
10011 cgi = CGI.new('html3')
10012
10013 cookname = "favorite ice cream"
10014 favorite = cgi.params["flavor"][0]
10015 tasty = cgi.cookies[cookname][0] || 'mint'
10016
10017 unless favorite
10018 cgi.out {
10019 cgi.html {
10020 cgi.head { cgi.title { "Ice Cookies" } } +
10021 cgi.body {
10022 cgi.h1 { "Hello Ice Cream" } +
10023 cgi.hr +
10024 cgi.form {
10025 cgi.p { "Please select a flavor: " +
10026 cgi.text_field("flavor", tasty ) }
10027 } +
10028 cgi.hr
10029 }
10030 }
10031 }
10032 else
10033 cookie = CGI::Cookie.new( "name" => cookname,
10034 "value" => favorite,
10035 "expires" => Time.local(Time.now.year + 2,
10036 Time.now.mon, Time.now.day, Time.now.hour, Time.now.min, Time.now.sec) )
10037 cgi.out("cookie" => [cookie]) {
10038 cgi.html {
10039 cgi.head { cgi.title { "Ice Cookies" } } +
10040 cgi.body {
10041 cgi.h1 { "Hello Ice Cream" } +
10042 cgi.p { "You chose as your favorite flavor `#{favorite}'." }
10043 }
10044 }
10045 }
10046 end
10047
10048
10049 # @@PLEAC@@_20.9
10050 def templatefile(filename, fillings)
10051 aFile = File.new(filename, "r")
10052 text = aFile.read()
10053 aFile.close()
10054 pattern = Regexp.new('%%(.*?)%%')
10055 text.gsub!(pattern) {
10056 fillings[$1] || ""
10057 }
10058 text
10059 end
10060
10061 fields = {
10062 'username' => whats_his_name,
10063 'count' => login_count,
10064 'total' => minutes_used
10065 }
10066 puts templatefile('simple.template', fields)
10067
10068 # @@INCOMPLETE@@
10069 # An example using databases is missing
10070