Skip to content

Instantly share code, notes, and snippets.

View zlx's full-sized avatar

Newell Zhu zlx

  • Hangzhou, China
View GitHub Profile
child_processes = 3
dead_processes = 0
# We fork 3 child processes.
child_processes.times do
fork do
# They sleep for 3 seconds.
sleep 3
end
end
fork do
5.times do
sleep 1
puts "I am an orphan!"
end
end
Process.wait
abort "Parent process died..."
fork do
5.times do
sleep 1
puts "I'm an orphan!"
end
end
abort "Parent process died..."
@zlx
zlx / fork.rb
Created June 15, 2014 06:17
An fork example
puts "parent process pid is #{Process.pid}"
if fork
puts "entered the if block from #{Process.pid}"
else
puts "entered the else block from #{Process.pid}"
end
def tag_errors
yield
rescue Exception => error
error.extend(Lib::Error)
end
t1 = Thread.new do
raise RuntimeError, "oops!" rescue $!
end
t2 = Thread.new do
raise ArgumentError, "doh!" rescue $!
end
puts "main: #{$!.inspect}"
puts "t1: #{t1.value.inspect}"
module NoDoubleRaise
def error_handled!
$! = nil
end
def raise(*args)
if $! && args.first != $!
warn "Double raise at #{caller.first}, aborting"
exit! false
else
@zlx
zlx / strip_squish
Created September 11, 2012 08:48
strip vs squish
[35] pry(main)> " strinsg ".strip
=> "strinsg"
[36] pry(main)> " strinsg ".squish
=> "strinsg"
[37] pry(main)> " strin sg ".strip
=> "strin sg"
[38] pry(main)> " strin sg ".squish
=> "strin sg"
@zlx
zlx / instance_of_and_is_a.rb
Created July 18, 2012 14:09
instance_of? and is_a?
# test is_a? and instance_of? methods
# instance_of? ignore the superclass
class SuperClass; end
class ChildClass < SuperClass ; end
b = ChildClass.new
puts b, b.instance_of?(SuperClass), b.is_a?(SuperClass)