Ruby __DATA__ (embedded data)

Aug 22
2008
module Kernel
  RE_THIS_DATA = lambda{ |number| /^__DATA#{number}__\n/ }
  RE_THE_DATA  = /^__DATA\d+__/
 
  def __data__(num="")
    data = File.read($0).split(RE_THIS_DATA.call(num))
    data[1].split(RE_THE_DATA)[0] if data[1]
  end
end
 
puts "DATA"
print __data__()
 
puts "DATA1"
print __data__(1)
 
puts "DATA2"
print __data__(2)
 
__END__
 
__DATA__
data_1
data_2
data_3
 
__DATA1__
data1_1
data1_2
data1_3
 
data1_11
 
__DATA2__
data2_1
data2_2
data2_3
 
data2_31

Chdir Method with Block

Aug 22
2008
# temporary changes the cwd to '/tmp',
# adds content to a file and finally restores cwd
 
p Dir.getwd
 
Dir.chdir("/tmp") do
  p Dir.getwd
  File.open("test.txt", "a") do |f|
    f << Time.now << "\n"
  end
end
 
p Dir.getwd

Fighting with Opera Bugs

Aug 21
2008

Thank to Opera plugins’ implementaion I had over 100% CPU laod (dual core).
The solution: rm /usr/lib/opera/9.52/operaplugincwrapper

Random strings

Aug 19
2008
module Kernel
  def random_uc(size=16)
    Array.new(size){ rand(26)+65 }.pack('C*')
  end
  def random_lc(size=16)
    Array.new(size){ rand(26)+97 }.pack('C*')
  end
  def random_num(size=16)
    Array.new(size){ rand(10) }.join
  end
end
 
random_uc => "HRTWYJBJEZDKYPTJ"
random_lc => "onxkvkezqukspmcx"
random_num => "5862195932579950"

Setting Core Objects’ Methods in RoR

Aug 09
2008

mkdir -p RAILS_ROOT/vendor/plugins/core_methods

mkdir -p RAILS_ROOT/vendor/plugins/core_methods/init.rb

The content of init.rb:

module Rails
 
  empty_and_nil = %q{def empty_and_nil; self.empty?? nil : self end}
 
  Array.send :class_eval, empty_and_nil
  Hash.send  :class_eval, empty_and_nil
 
end

The namespace Rails isn’t necessary, it’s a cosmetic feature.

Return nil Instead Of empty Array instance

Aug 08
2008
class Array
  def empty_and_nil
    self.empty?? nil : self
  end
end
 
result = [1,2,3].empty_and_nil # [1, 2, 3]
result = [].empty_and_nil        # nil

How false Is nil

Aug 04
2008

Use nil when the return is a boolean value.
Use false when the return is either false or not true object.
Otherwise they have pretty much the same semantic:

nil == false => false
nil.nil?        => true
false.nil?     => false
true.nil?      => false
 
if !nil && !false
  puts 'true'
end
 
if nil.nil? && !true.nil?
  puts 'true'
end
 
>> TrueClass.ancestors
=> [TrueClass, Object, Kernel]
>> FalseClass.ancestors
=> [FalseClass, Object, Kernel]
>> NilClass.ancestors
=> [NilClass, Object, Kernel]

Ruby core docs

Remove All Empty Directories

Aug 04
2008
alias _rmdir_empty='rmdir * 2>/dev/null'

Multiplication Table In AoH Structure

Aug 03
2008
mt = Array.new(10) { |e| Hash.new { |h,k| h[k] = k * e } }
 
mt[1][2] => 2
mt[2][2] => 4
mt[5][4] => 20
mt[9][5] => 45

Calendar

August 2008
M T W T F S S
« Jul   Sep »
 123
45678910
11121314151617
18192021222324
25262728293031

Tags