Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Measuring the elapsed time

This Ruby code measures how long it takes to display the message "hello world".
def test_method(statement)
  start_time = Time.now
  eval(statement)
  end_time = Time.now
  end_time - start_time
end

statement = "sleep 1.5; puts 'hello world'"
elapsed_time = test_method(statement)
puts "elapsed time : #{elapsed_time}"

output
hello world
elapsed time : 1.499266

Ruby Servlets

This WEBrick example demonstrates a basic servlet which displays the current time. Source code copied from At the Forge - Getting Started with Ruby [linuxjournal.com].

#!/sw/bin/ruby
require 'webrick'
include WEBrick

# ---------------------------------------------
# Define a new class
class CurrentTimeServlet
  < WEBrick::HTTPServlet::AbstractServlet

  def do_GET(request, response)
    response['Content-Type'] = 'text/plain'
    response.status = 200
    response.body = Time.now.to_s + "\n"
  end
end

# ----------------------------------------------
# Create an HTTP server
s = HTTPServer.new(
  :Port            => 8000,
  :DocumentRoot    => "/usr/local/apache/htdocs/"
)

s.mount("/time", CurrentTimeServlet)

# When the server gets a control-C, kill it
trap("INT"){ s.shutdown }

# Start the server
s.start

e.g. http://localhost:8001/time
output
Mon Mar 10 23:06:58 +0000 2008

Reference: http://www.webrick.org/

Creating a DateTime object with Ruby

This example creates a date and time variable which represents 22nd March 2008 4:30pm and 12 seconds.
d2 = DateTime.new(y=200,m=3,d=22, h=16,min=30,s=12)

or convert a date string into a DataTime object:
"17/03/2009 17:48:00"[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
d2 = DateTime.new(y=$3.to_i,m=$2.to_i,d=$1.to_i, h=$4.to_i,min=$5.to_i,s=$6.to_i)

or convert a date string into a Time object:
"22/03/2008 17:48:00"[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
iyear = $3.to_i; imonth = $2.to_i; iday = $1.to_i; ihour = $4.to_i; imin = $5.to_i; isec = $6.to_i
twork = Time.local(iyear,imonth,iday,ihour,imin,isec) 
puts 'we still have time to party' if Time.now < twork 

Reference:
Class: DateTime [ruby-doc.org]
Class: Time [ruby-doc.org]
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS