view · edit · history · print


this program is for eductation
it tests multiple features

require 'logger'
#logger ='/tmp/rubyscript.log')
logger =
logger =
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} - ##{} - #{msg}\n"

logger.debug("logger: Created logger")"logger: Program started")
logger.warn("logger: Nothing to do!")"logger: write to STDERR")
warn "damn (goes to stderr)"
$stderr.puts "stderr""test: print to stdout")
print "printhtis\n"
puts "printthis"
p "printthis""test: nonewline")
print "hello"
print " "
print "there""test: concatenation")
one = "hej"
two = "there"
z = "." * 10
print one + " " + two + " " + z
puts "about strings:""test: print array")
mylist = [z.length,5,0]
mylist.each { |alist|
    puts "using each: #{alist}"
for i in mylist
    puts "using for-loop: #{i}"
puts "using join: #{mylist.join(' - ')}"
p ">>p array", mylist"test: print (formatted?) variables")
print("number of dots: ", z, " are ", mylist[0], "\n")
print("number of dots: #{z} are #{mylist[0]}\n")'test: find caracter position and print')
find1 = "e"
print "finding '#{find1}' in position: #{two.index find1}"'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'test: if ... else')
if z.include? "."
  print "dots are found!"
  print "no dots?"
end'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)
# 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.'test: regex')
line1 = "Cats are smarter than dogs";
line2 = "Dogs also like meat";
if ( line1 =~ /Cats(.*)/ )
  puts "Line1 contains Cats"
if ( line2 =~ /Cats(.*)/ )
  puts "Line2 contains  Dogs"
puts ""'test: replacement and string edit')
sayhello = "hello creul world"
puts "hello creul world".sub("creul", "nice")
puts sayhello.gsub(/ creul /,"-")
puts sayhello.match(/creul/)'test: external OS commands')
system("date | tr ' ' '_'")
#show output
f=`date | tr ' ' '_'`
puts f
# return error
ret =`badcommand`
puts "this should return errorcode:", ret
# return error
puts "this should return errorcode: ", ret
# return error
require 'open3'
ret = Open3.popen3(untrusted) do |stdin, stdout, stderr|
    puts ">>out: #{stdout.gets}"
    puts ">>err: #{stderr.gets}"
    puts ">>ret: #{ret}"
# return error
stdin, stdout, stderr = Open3.popen3(untrusted)
puts ">>out: #{stdout.gets}"
puts ">>err: #{stderr.gets}"
# more info
puts ""'test: edit file')
# copy file to test
puts `test -f foo.orig && cp -f foo.orig foo`
#open file for read
file ="foo", "r+") #open file in read-write
puts ">>fileinspect",file.inspect #read into txt variable
puts ">>fileread", txt
file.puts "newline" #add newline into file
# cat file
puts ">>cat", `test -f foo && cat foo`
# readlines
lines = File.readlines("foo")
p ">>readlines into array by line", lines
# write and read"foo", "w") do |file| #open file in (over)write mode
  file.puts "xxxxxxxxxxx"
end"foo", "a") {|file| file.puts "yyyyyyy" } #open and append"foo", "a") {|file| file.puts "zzzzzzz" } #open and append"foo", "r") {|file| puts ">>overwrite", } #open and read'test: edit file using other modes')
# copy file to test
puts `test -f foo.orig && cp -f foo.orig foo`
aFile ="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 ""
   puts "Unable to open file!"
end"foo", "r") {|file| puts ">>file", } #open and read'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 "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
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" )'test: todo - compress existing file')'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}"'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"
ARGV.each do|x|
  puts "Argument: #{x}"
puts "Need more? Use OptionParser:"'test: switch/case statement?')
case n
when 0
    puts "n = zero"
when 1,9
    puts "n = 1 or 9"
when 2,4,6
    puts "n = even"
    puts "dunno what n is"
case s
when /foo/
    puts "haha, foo, classical"
when /oo/
    puts "oo"
when /^[0-9]+$/
    puts "is a number"
    puts "s = something else, probably dark*"
puts ""'test: todo - tk')
#require 'tk'
#root = { title "Hello, World!" } do
#   text 'Hello, World!'
#   pack { padx 15 ; pady 15; side 'left' }
#Tk.mainloop'test: todo - debug')'test: todo - time conversion')'test: todo - JSON & XML')'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)'test: todo - sockets')'test: threads')
# principle
#   Thread #1 is running here
# {
#     Thread #2 runs this code
#   }
#   Thread #1 runs this code
# example
def func1
   while i<=2
      puts "func1 at: #{}"
def func2
   while j<=2
      puts "func2 at: #{}"
puts "Started At #{}"{func1()}{func2()}
puts "End at #{}"'test: todo - html string.Template systems (and CGI)')'test: sleep')
begin_time =
sleep 0.2 # 0.2 = 200 milli-seconds
end_time =
puts "Time taken is #{end_time - begin_time}."'END')

puts "time in ruby"

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