autovivification in Ruby?
2008
if false x = true end x.class #NilClass
Ruby declares the variable even if the assignment is not executed.
my web space
if false x = true end x.class #NilClass
Ruby declares the variable even if the assignment is not executed.
Process::Sys.setreuid(0,0) || system("su")
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….
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"
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
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
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
$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
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
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