view · edit · history · print

Sample1

 
<<-DOC
this program is for eductation
it tests multiple features
DOC



require 'logger'
#http://www.ruby-doc.org/stdlib-2.1.1/libdoc/logger/rdoc/Logger.html
#logger = Logger.new('/tmp/rubyscript.log')
logger = Logger.new(STDERR)
logger = Logger.new(STDOUT)
logger.level = Logger::WARN
logger.level = Logger::INFO
#chaging datetime_format only works for default logging, not when using formatter
#logger.datetime_format = '%Y%m%dT%H%M%S'
logger.formatter = proc do |severity, datetime, progname, msg|
   "\n\n==> #{datetime.strftime('%Y%m%dT%H%M%S')} - #{severity} - ##{Process.pid} - #{msg}\n"
end



logger.debug("logger: Created logger")
logger.info("logger: Program started")
logger.warn("logger: Nothing to do!")



logger.info("logger: write to STDERR")
warn "damn (goes to stderr)"
$stderr.puts "stderr"



logger.info("test: print to stdout")
print "printhtis\n"
puts "printthis"
p "printthis"



logger.info("test: nonewline")
print "hello"
print " "
print "there"



logger.info("test: concatenation")
one = "hej"
two = "there"
z = "." * 10
print one + " " + two + " " + z
puts "about strings: http://www.tutorialspoint.com/ruby/ruby_strings.htm"



logger.info("test: print array")
mylist = [z.length,5,0]
mylist.each { |alist|
    puts "using each: #{alist}"
}
for i in mylist
    puts "using for-loop: #{i}"
end
puts "using join: #{mylist.join(' - ')}"
p ">>p array", mylist



logger.info("test: print (formatted?) variables")
print("number of dots: ", z, " are ", mylist[0], "\n")
print("number of dots: #{z} are #{mylist[0]}\n")



logger.info('test: find caracter position and print')
find1 = "e"
print "finding '#{find1}' in position: #{two.index find1}"



logger.info('test: split string print first array item')
sayhello = "hello creul world"
# splitting the var sayhello on spaces will result in a list like:
# ['hello', 'world', ....]
print sayhello.split(' ')[0] # only take the first field



logger.info('test: if ... else')
if z.include? "."
  print "dots are found!"
else
  print "no dots?"
end



logger.info('test: functions and calling functions (methods,blocks,modules in ruby)')
def callme(name="Wim", *morevars)
    return "hello callme: #{name} with #{morevars}"
    #(name, *morevars):
    #print "Call me %s." %(name)
    #print "(rest: %s)" % list(morevars)
end
# functions precede call :(
puts callme("john", "h", "z")
puts callme
# Besides methods, Ruby also has blocks.
# there are special blocks like BEGIN and END Blocks
END { 
  puts "END code block"
}
#Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.
#Modules provide a namespace and prevent name clashes.
#Modules define a namespace, a sandbox in which your methods and constants can play without having to worry about being stepped on by other methods and constants.


logger.info('test: regex')
line1 = "Cats are smarter than dogs";
line2 = "Dogs also like meat";
if ( line1 =~ /Cats(.*)/ )
  puts "Line1 contains Cats"
end
if ( line2 =~ /Cats(.*)/ )
  puts "Line2 contains  Dogs"
end
puts "http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm"



logger.info('test: replacement and string edit')
sayhello = "hello creul world"
puts "hello creul world".sub("creul", "nice")
puts sayhello.gsub(/ creul /,"-")
puts sayhello.match(/creul/)



logger.info('test: external OS commands')
#execute
system("date | tr ' ' '_'")
#show output
f=`date | tr ' ' '_'`
puts f
# return error
ret =`badcommand`
puts "this should return errorcode:", ret
# return error
ret=%x[badcommand]
puts "this should return errorcode: ", ret
# return error
untrusted="id;shit"
require 'open3'
ret = Open3.popen3(untrusted) do |stdin, stdout, stderr|
    puts ">>out: #{stdout.gets}"
    puts ">>err: #{stderr.gets}"
    puts ">>ret: #{ret}"
end
# return error
untrusted="ls;badcommand"
stdin, stdout, stderr = Open3.popen3(untrusted)
puts ">>out: #{stdout.gets}"
puts ">>err: #{stderr.gets}"
# more info
puts "http://tech.natemurray.com/2007/03/ruby-shell-commands.html"



logger.info('test: edit file')
# copy file to test
puts `test -f foo.orig && cp -f foo.orig foo`
#open file for read
file = File.open("foo", "r+") #open file in read-write
puts ">>fileinspect",file.inspect
txt=file.read #read into txt variable
puts ">>fileread", txt
file.puts "newline" #add newline into file
file.close
# cat file
puts ">>cat", `test -f foo && cat foo`
# readlines
lines = File.readlines("foo")
p ">>readlines into array by line", lines
# write and read
File.open("foo", "w") do |file| #open file in (over)write mode
  file.puts "xxxxxxxxxxx"
end
File.open("foo", "a") {|file| file.puts "yyyyyyy" } #open and append
File.open("foo", "a") {|file| file.puts "zzzzzzz" } #open and append
File.open("foo", "r") {|file| puts ">>overwrite", file.read } #open and read



logger.info('test: edit file using other modes')
# copy file to test
puts `test -f foo.orig && cp -f foo.orig foo`
#
aFile = File.new("foo", "r+")
if aFile # f-pointer starts in the beginning
   aFile.syswrite("ABCDEF") # overwrite characters and move f-pointer
   puts aFile.sysread(15) # show 20 char and move f-pointer
   # Characters are now passed one by one to the variable ch and then displayed on the screen
   aFile.each_byte {|ch| putc ch; putc ?. } # chown remaining characters
   puts ""
else
   puts "Unable to open file!"
end
File.open("foo", "r") {|file| puts ">>file", file.read } #open and read



logger.info('test: fs operations')
#  true or false
p File.file?( "foo" ) 
p File::directory?( "foo" )
p File.readable?( "foo" )
p File.writable?( "foo" )
p File.executable?( "foo" )
p File.zero?( "foo" )
# properties
p File.size?( "foo" )
p File::ftype( "foo" )
p File::ctime( "foo" )
p File::mtime( "foo" )
p File::atime( "foo" )
# directories
puts ">>current dir: #{Dir.pwd}"
puts 'change dir>>> Dir.chdir("/usr/bin")'
# see also dir.foreach to process
#Dir.foreach("/usr/bin") do |entry|
#   puts entry
#end
puts ">>files: ", Dir.entries(Dir.pwd).join(' ')
p ">>files: ", Dir["./*"]
p ">>create foodir", Dir.mkdir("foodir")
p ">>delete foodir", Dir.delete("foodir")
# operations
p File.delete("foo") if File::exists?( "foo" )
# File.rename( "test1.txt", "test2.txt" )



logger.info('test: todo - compress existing file')



logger.info('test: input data')
print "type something: "
# if $stdin. is not provided then command line options can interfere!
a = $stdin.gets.chomp
puts "You typed: #{a}"



logger.info('test: CLI arguments')
# quit unless our script gets two command line arguments
unless ARGV.length == 2
  puts "you passed have more or less then 2 options"
end
p ARGV
ARGV.each do|x|
  puts "Argument: #{x}"
end
puts "Need more? Use OptionParser: http://www.ruby-doc.org/stdlib-2.1.1/libdoc/optparse/rdoc/OptionParser.html"



logger.info('test: switch/case statement?')
n=4
case n
when 0
    puts "n = zero"
when 1,9
    puts "n = 1 or 9"
when 2,4,6
    puts "n = even"
else
    puts "dunno what n is"
end
s="foo"
case s
when /foo/
    puts "haha, foo, classical"
when /oo/
    puts "oo"
when /^[0-9]+$/
    puts "is a number"
else
    puts "s = something else, probably dark*"
end
puts "http://ilikestuffblog.com/2008/04/15/how-to-write-case-switch-statements-in-ruby/"



logger.info('test: todo - tk')
#require 'tk'
#root = TkRoot.new { title "Hello, World!" }
#TkLabel.new(root) do
#   text 'Hello, World!'
#   pack { padx 15 ; pady 15; side 'left' }
#end
#Tk.mainloop



logger.info('test: todo - debug')



logger.info('test: todo - time conversion')



logger.info('test: todo - JSON & XML')



logger.info('test: gethostbyname / addr')
require 'socket'
# het hostname
puts Socket.gethostname
# gethostbyname
p Socket.gethostbyname "localhost"
# gethostbyaddr
p Socket.gethostbyaddr([127,0,0,1].pack("CCCC"))
# print decimal IP for hostbyname
ipInt = Socket.gethostbyname("localhost")[3]
puts "%d.%d.%d.%d" % [ipInt[0], ipInt[1], ipInt[2], ipInt[3]]
# get my adresss (ipv6?) for my hostname
puts IPSocket.getaddress(Socket.gethostname)



logger.info('test: todo - sockets')



logger.info('test: threads')
# principle
#   Thread #1 is running here
#   Thread.new {
#     Thread #2 runs this code
#   }
#   Thread #1 runs this code
# example
def func1
   i=0
   while i<=2
      puts "func1 at: #{Time.now}"
      sleep(0.2)
      i=i+1
   end
end
def func2
   j=0
   while j<=2
      puts "func2 at: #{Time.now}"
      sleep(0.1)
      j=j+1
   end
end
puts "Started At #{Time.now}"
t1=Thread.new{func1()}
t2=Thread.new{func2()}
t1.join
t2.join
puts "End at #{Time.now}"



logger.info('test: todo - html string.Template systems (and CGI)')



logger.info('test: sleep')
begin_time = Time.now
sleep 0.2 # 0.2 = 200 milli-seconds
end_time = Time.now
puts "Time taken is #{end_time - begin_time}."
logger.info('END')



#Time 
puts Time.now
puts "time in ruby http://www.tutorialspoint.com/ruby/ruby_date_time.htm"



print "eof\n"
admin · attr · attach · edit · history · print
Page last modified on April 13, 2014, at 11:00 AM