<< Previous Page
    

    
      Table of Contents
    

    
      Next Page >>
    
  
08
%q{TSort}
# TSort sorts by dependency
# To use TSort, patch the Hash class:
require 'tsort'

class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end

# Simple usage:
{a: [:b], b: []}.tsort
=> [:b, :a]

# Can depend on multiple things
{a: [:c, :b], b: [:c], c: []}.tsort
=> [:c, :b, :a]

# All keys independent
{a: [], b: [], c: []}.tsort
=> [:a, :b, :c]

# Given an empty hash
{}.tsort
=> [] # Empty

# All keys must exist in hash
{a: [:b], c: []}.tsort
# KeyError: key not found: :b


%q{PP}
require 'pp'
%q{ARGF}
# Say we have a script:
# script.rb
p ARGF.read

# If given data via stdin:
# echo hello | ruby script.rb
=> "hello\n"

# Pass a file name to the script:
# ruby script.rb file.txt
=> "contents of file.txt"

# Pass two file names to the script:
# ruby script.rb file.txt file2.txt
=> "contents of file.txt\ncontents of file2.txt\nyes\n"

# You can read their lines separately with readlines

# script.rb
ARGF.readlines

# ruby script.rb file.txt file2.txt
=> ["contents of file.txt\n", "contents of file2.txt\n", "yes\n"]

# Can detect cycles
{a: [:b], b: [:a]}.tsort
TSort::Cyclic:
topological sort failed: [:a, :b]

# Works on any type
{a: [:b], b: ['a'], 'a'=> []}.tsort
=> ["a", :b, :a]
# Acts the same as #p if the line is not long
pp({a: 5, b:6, c:{a:1}, d: {b:1, c:1}, e: {f:{g:1, h:1}} })
=> {:a=>5, :b=>6, :c=>{:a=>1}, :d=>{:b=>1, :c=>1}, :e=>{:f=>{:g=>1, :h=>1}}}

p({a: 5, b:6, c:{a:1}, d: {b:1, c:1}, e: {f:{g:1, h:1}} })
=> {:a=>5, :b=>6, :c=>{:a=>1}, :d=>{:b=>1, :c=>1}, :e=>{:f=>{:g=>1, :h=>1}}}

# But if it is longer it will begin to format the strings
pp({a: 5, b:6, d: {b:1, c:1}, e: {f:{g:1, h:1123123123123}} })
=> {:a=>5,
:b=>6,
:d=>{:b=>1, :c=>1},
:e=>{:f=>{:g=>1, :h=>1123123123123}}}

# Works with arrays too
pp [1,2,a:'4'*20,b:'x'*30,c:'z'*23]
=>[1,
2,
{:a=>"44444444444444444444",
:b=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
:c=>"zzzzzzzzzzzzzzzzzzzzzzz"}]
08
    
      << Previous Page
    

    
      Table of Contents
    

    
      Next Page >>