autovivification in Ruby?

Apr 13
2008
if false
 x = true
end
 
x.class #NilClass

Ruby declares the variable even if the assignment is not executed.

sudo with Ruby

Apr 13
2008
Process::Sys.setreuid(0,0) || system("su")

Ruby system administration scripts

Mar 22
2008

OS users:

users = File.new("/etc/passwd").collect{|x| x.split(':')[0]}

Number of files in directory:

puts %x{ls}.split(/\n/).size
puts %x[ls|wc].split(/\s+/)[1]

Network interfaces:

inet = Hash.new{|h,k| h[k.split(/\s/)[0]] = k.scan(/addr:(\d+\.\d+\.\d+\.\d+)/)[0].to_s}
 
%x[ifconfig].to_s.split("\n\n").collect{|x| inet[x]}
 
# dump the structure: puts inet.inspect

to be continued….

Scalar || List context

Feb 12
2008

Perl

 $a  = ("a", "b", "c"); # $a is "c" - the last element
($a) = ("a", "b", "c"); # $a is "a" - the first element

Ruby

 obj        = ["a", "b", "c"] # obj is Array - ["a", "b", "c"]
 obj, b, c = ["a", "b", "c"] # obj is String - "a"

Lotto checking script

Feb 12
2008

The idea comes from http://www.waider.ie/hacks/workshop/perl/lotto.pl script.

Should I be so wasteful? No:

irb

my_numbers       = [1,2,3,4,5,6]
winning_numbers = [1,2,3,41,42,43]
 
result = 6 - (winning_numbers - my_numbers).size
 
puts "#{result} " +
  if not result.eql? 0
    "hits"
  else
    "hit"
  end

Sample .irbrc (with autocomplete)

Feb 02
2008
cp .irbrc $HOME; irb
require "irb/completion"
 
IRB.conf[:PROMPT_MODE] = :SIMPLE
 
def ri(*arg)
  system("ri #{arg.join" "}")
end
 
class Object
  def __find_method(reg=Regexp.new)
     self.methods.sort.grep reg
  end
 
  alias :fm :__find_method
end

String Iterator

Jan 14
2008
class String
  class Iterator < String
 
    def initialize(str='', next_char=0)
      @next_char = next_char
      super(str)
    end
 
    def next
      return nil if @next_char > self.size
 
      @next_char += 1
 
      get_char(-1)
    end
 
    def prev
      return nil if @next_char < = 0
 
      @next_char -= 1 if @next_char > 0
 
      get_char()
    end
 
    private
    def get_char(pos=0)
      if block_given?
        yield split(//)[@next_char+(pos)]
      else
        split(//)[@next_char+(pos)]
      end
    end
  end
end
 
s = String::Iterator.new "abcdef"
 
while char = s.next
  puts char
end
 
while char = s.prev
  puts char
end

Getting Ruby Include Path

Jan 13
2008
$LOAD_PATH === $: #true, hence

irb

puts$:.sort
 
__END__
.
/usr/lib/ruby/1.8
/usr/lib/ruby/1.8/i386-linux
/usr/lib/ruby/1.8/i486-linux
/usr/local/lib/site_ruby
/usr/local/lib/site_ruby/1.8
/usr/local/lib/site_ruby/1.8/i386-linux
/usr/local/lib/site_ruby/1.8/i486-linux

File.rename(tedious part of the filename)

Jan 13
2008

Rename each file in each sub-directory, substituting ‘%20’ with ’ ‘(space).

class File
  def self.rename_basename(abs_name, old_str, new_str)
    f_name = File.basename(abs_name).gsub Regexp.quote(old_str), new_str
    d_name = File.dirname(abs_name)
    File.rename(abs_name, d_name + '/' + f_name)
    rescue
      raise ArgumentError, "No such file #{filename}", caller
  end
end
 
Dir["*/**"].each do |f|
  if File.basename(f).match('%20')
    File.rename_basename(f, '%20', ' ')
  end
end

Sort By Part Of Filename

Jan 12
2008

Assume that we have directory, containing files like:

part_1.txt
part_2.txt
part_100.txt
part_200.txt

In case that we are interested in /(\d+)\.\w+$/ as part of the sorting criteria:

Perl

# short but unefficient
@a = sort {($a =~ /(\d+)\.\w+$/)[0] < => ($b =~  /(\d+)\.\w+$/)[0]} < *>;

Ruby

regex = Regexp.new(/(\d+)\.\w+$/)
 
# enum.sort {| a, b | block } => array
Dir["*"].grep(regex).sort do |a, b|
  a.match(regex)[0].to_i < => b.match(regex)[0].to_i
end
 
# enum.sort_by {| obj | block } => array
Dir["*"].grep(regex).sort_by do |name|
  name.match(regex)[1].to_i
end

Calendar

May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  

Tags