Week #5 Challenge: Ruby

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

38 Replies - 9778 Views - Last Post: 19 August 2010 - 10:11 PM

#16 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 445
  • View blog
  • Posts: 1,501
  • Joined: 28-April 09

Re: Week #5 Challenge: Ruby

Posted 01 February 2010 - 06:52 PM

View PostShane Hudson, on 1 Feb, 2010 - 10:25 AM, said:

This is a Number to Roman Numeral script, functions well however I am not experienced in Ruby and am not sure how I can get it so that 4 = IV instead of IIII.

If anybody can help, please do!


Not sure if this is the best way, but it seems to work for me


def get_roman_numeral(int, rn)
	values = {1000 => 'M', 900 => 'CM', 500 => 'D', 400 => 'CD', 100 => 'C', 90 => 'XC', 50 => 'L', 40 => 'XL', 10 => 'X', 9 => 'IX', 5 => 'V', 4 => 'IV', 1 => 'I'}
			  
	values.each_pair do |key, value|
		if int >= key
			rn.push(value)
			return get_roman_numeral(int - key, rn)
		end
	end

	return rn
end

puts 'Enter a number to be converted to a Roman numeral'
int = gets.chomp.to_i

original_int = int
roman_numeral = Array.new
roman_numeral = get_roman_numeral(int, roman_numeral)

numeral = ''

roman_numeral.each() do |r_numeral|
	numeral = numeral + r_numeral
end

puts "#{original_int}, when converted to a Roman numeral, is #{numeral}!"



This post has been edited by Nakor: 01 February 2010 - 07:10 PM

Was This Post Helpful? 0
  • +
  • -

#17 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Week #5 Challenge: Ruby

Posted 01 February 2010 - 08:06 PM

Quote

Ruby is a scripting Language


God damn you.

Also, for more ideas for Ruby programs here is a quiz site similar to Perl's quiz site with various problems at various difficulties:

http://rubyquiz.com/index.html

This post has been edited by Dark_Nexus: 01 February 2010 - 08:11 PM

Was This Post Helpful? 2
  • +
  • -

#18 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 611
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 02:18 AM

Ruby doesn't have to be used just for scripting, though it definitely lends well to such things.
Was This Post Helpful? 0
  • +
  • -

#19 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 03:31 AM

I can agree with that. Mostly due to its performance though (which is supposed to be better in 1.9)

Think I am gonna try a couple of the quizes (starting with this one) when I wake up tomorrow:

http://rubyquiz.com/quiz14.html

This post has been edited by Dark_Nexus: 02 February 2010 - 03:39 AM

Was This Post Helpful? 0
  • +
  • -

#20 Paul-  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 61
  • View blog
  • Posts: 260
  • Joined: 11-December 09

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 06:18 AM

Thanks for this interesting challenge. It was a good excuse for me to look at Ruby. Here is a class for rational numbers, with the basic arithmetic operations implemented.

# Class of rational numbers
# implements basic arithmetic operations

class Q
  def initialize (n,d)
    n = n.to_i
    d = d.to_i
    if d == 0
      @undef = true
    else
      @undef = false
      if n*d < 0
        @positive = false
      else
        @positive = true
      end
      n = n.abs
      d = d.abs
      gcd = Q.gcd(n,d)
      @numerator = n/gcd
      @denominator = d/gcd
    end
  end

  # for printing
  def to_s()
    if @undef
      'NaN'
    elsif @numerator == 0
      '0'
    else
      sign = ''
      if !@positive
        sign = '-'
      end
      sign + @numerator.to_s + "/" + @denominator.to_s
    end
  end

  # overloaded addition operator
  def + (t2)
    n = 0
    d = 0
    if !@undef && !t2.undef
      n1 = @numerator*t2.denominator
      if !@positive
        n1 = -n1
      end
      n2 = t2.numerator*@denominator
      if !t2.positive
        n2 = -n2
      end
      n = n1 + n2
      d = @denominator*t2.denominator
    end
    Q.new(n,d)
  end

  # overloaded subtraction operator
  def - (t2)
    n = 0
    d = 0
    if !@undef && !t2.undef
      n1 = @numerator*t2.denominator
      if !@positive
        n1 = -n1
      end
      n2 = t2.numerator*@denominator
      if t2.positive
        n2 = -n2
      end
      n = n1 + n2
      d = @denominator*t2.denominator
    end
    Q.new(n,d)
  end

  # overloaded multiplication operator
  def * (t2)
    n = 0
    d = 0
    if !@undef && !t2.undef
      n = @numerator*t2.numerator
      d = @denominator*t2.denominator
      if @positive ^ t2.positive
        n = -n
      end
    end
    Q.new(n,d)
  end

  # overloaded division operator
  def / (t2)
    n = 0
    d = 0
    if !@undef && !t2.undef
      n = @numerator*t2.denominator
      d = @denominator*t2.numerator
      if @positive ^ t2.positive
        n = -n
      end
    end
    Q.new(n,d)
  end

  # Algorithm of Euclid to compute GCD of two non-negative integers
  def Q.gcd (nlarge, nsmall)
    if nlarge < nsmall
      tmp = nlarge
      nlarge = nsmall
      nsmall = tmp
    end
    
    while nsmall > 0
      tmp = nlarge - nsmall
      if tmp < nsmall
        nlarge = nsmall
        nsmall = tmp
      else
        nlarge = tmp
      end
    end
    nlarge
  end

  # accessor methods for class instance variables
  attr_accessor :undef
  attr_accessor :positive
  attr_accessor :numerator
  attr_accessor :denominator
end

# testing
q1 = Q.new(-10,20)
q2 = Q.new(5,15)
puts q1.to_s + " + " + q2.to_s + " = " + (q1 + q2).to_s
puts q1.to_s + " - " + q2.to_s + " = " + (q1 - q2).to_s
puts q1.to_s + " * " + q2.to_s + " = " + (q1 * q2).to_s
puts q1.to_s + " / " + q2.to_s + " = " + (q1 / q2).to_s
puts

q1 = Q.new(2,8)
q2 = Q.new(3,-18)
puts q1.to_s + " + " + q2.to_s + " = " + (q1 + q2).to_s
puts q1.to_s + " - " + q2.to_s + " = " + (q1 - q2).to_s
puts q1.to_s + " * " + q2.to_s + " = " + (q1 * q2).to_s
puts q1.to_s + " / " + q2.to_s + " = " + (q1 / q2).to_s
puts

q1 = Q.new(3,15)
q2 = Q.new(0,8)
puts q1.to_s + " + " + q2.to_s + " = " + (q1 + q2).to_s
puts q1.to_s + " - " + q2.to_s + " = " + (q1 - q2).to_s
puts q1.to_s + " * " + q2.to_s + " = " + (q1 * q2).to_s
puts q1.to_s + " / " + q2.to_s + " = " + (q1 / q2).to_s
puts

q1 = Q.new(2,8)
q2 = Q.new(-3,0)
puts q1.to_s + " + " + q2.to_s + " = " + (q1 + q2).to_s
puts q1.to_s + " - " + q2.to_s + " = " + (q1 - q2).to_s
puts q1.to_s + " * " + q2.to_s + " = " + (q1 * q2).to_s
puts q1.to_s + " / " + q2.to_s + " = " + (q1 / q2).to_s
puts


Was This Post Helpful? 0
  • +
  • -

#21 carltech  Icon User is offline

  • What did you call me?
  • member icon

Reputation: 28
  • View blog
  • Posts: 997
  • Joined: 19-October 07

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 01:12 PM

just like with the python challenge I have already done some Ruby. I took a class that was taught in python, nut learned Ruby for fun.

Maybe I'll brush up on some ruby on rails stuff or maybe I'll make a little game or something but probably nothing to post about.
Was This Post Helpful? 0
  • +
  • -

#22 erik.price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 02:09 PM

View PostDark_Nexus, on 01 February 2010 - 10:06 PM, said:

<!--quoteo--><div class='quotetop'>QUOTE</div><div class='quotemain'><!--quotec-->Ruby is a scripting Language<!--QuoteEnd--></div><!--QuoteEEnd-->

God damn you.

Also, for more ideas for Ruby programs here is a quiz site similar to Perl's quiz site with various problems at various difficulties:

<a href="http://rubyquiz.com/index.html" target="_blank">http://rubyquiz.com/index.html</a>


Awesome site. I'll be sure to use that.

edit: apparently you can't quote links?

This post has been edited by erik.price: 02 February 2010 - 02:10 PM

Was This Post Helpful? 0
  • +
  • -

#23 skyhawk133  Icon User is offline

  • Head DIC Head
  • member icon

Reputation: 1877
  • View blog
  • Posts: 20,284
  • Joined: 17-March 01

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 02:13 PM

We just haven't finished re-building the posts table yet, takes MANY MANY hours and we have to do it at night. It'll run this evening hopefully.
Was This Post Helpful? 0
  • +
  • -

#24 poncho4all  Icon User is offline

  • D.I.C Head!
  • member icon

Reputation: 123
  • View blog
  • Posts: 1,405
  • Joined: 15-July 09

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 04:24 PM

Program to check for palindrome
var1 = 1
puts "Program to check if word is palindrome"
puts "Write a word"
STDOUT.flush
while var1 == 1
    palindrom = gets.chomp
    if palindrom == palindrom.reverse
      puts "The word is palindrom"
      puts "do you want to continue?"
      puts "1 = yes"
      puts "2 = no"
      STDOUT.flush
      var1 = gets.chomp
    else
      puts "try again"
      STDOUT.flush
    end
end

Was This Post Helpful? 0
  • +
  • -

#25 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 09:27 PM

# Converts input strings to LED-style
# displays on the terminal.

class LED 
	attr_accessor(:size, :spacing)

	@@states = [
		:horizontal, 
		:vertical,
		:horizontal,
		:vertical,
		:horizontal
	]

	@@num_map = {
		0 => [:line, :both, :none, :both, :line],
		1 => [:none, :right, :none, :right, :none],
		2 => [:line, :right, :line, :left, :line],
		3 => [:line, :right, :line, :right, :line],
		4 => [:none, :both, :line, :right, :none],
		5 => [:line, :left, :line, :right, :line],
		6 => [:line, :left, :line, :both, :line],
		7 => [:line, :right, :none, :right, :none],
		8 => [:line, :both, :line, :both, :line],
		9 => [:line, :both, :line, :right, :line]
	}

	def initialize(size = 1, spacing = 1)
		@size = size
		@spacing = spacing
	end

	def draw_horizontal(type)
		case type
		when :line
			return " " + ("_" * @size) + " " + (" " * @spacing)
		else
			return " " + (" " * @size) + " " + (" " * @spacing)
		end
	end

	def draw_vertical(type)
		case type
		when :left
			return "|" + (" " * @size) + " " + (" " * @spacing)
		when :right
			return " " + (" " * @size) + "|" + (" " * @spacing)
		when :both
			return "|" + (" " * @size) + "|" + (" " * @spacing)
		else
			return " " + (" " * @size) + " " + (" " * @spacing)
		end
	end

	def display(digits)
		for i in (0..(@@states.length))
			case @@states[i]
			when :horizontal 
				line = ""
				digits.each do |d|
					line += draw_horizontal(@@num_map[d.to_i][i])
				end
				puts line
			else
				line = ""
				@size.times do
					digits.each do |d|
						line += draw_vertical(@@num_map[d.to_i][i])
					end
					line += "\n"
				end
				print line
			end
		end
	end
end			



This ends up looking a lot like the posted solution on the quiz site. Probably cause I decided to go with their encoding scheme and I liked the idea of using the size and spacing options as well.

This post has been edited by Dark_Nexus: 02 February 2010 - 09:27 PM

Was This Post Helpful? 0
  • +
  • -

#26 skyhawk133  Icon User is offline

  • Head DIC Head
  • member icon

Reputation: 1877
  • View blog
  • Posts: 20,284
  • Joined: 17-March 01

Re: Week #5 Challenge: Ruby

Posted 02 February 2010 - 09:28 PM

Nice work!
Was This Post Helpful? 0
  • +
  • -

#27 njovin  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 6
  • Joined: 31-January 10

Re: Week #5 Challenge: Ruby

Posted 04 February 2010 - 12:37 AM

SMTP LOG TOOL
---
First ruby script ever. Decided to do something useful this time. As a part-time mail admin I spend some time sifting through mail logs. Usually just CTRL+F with notepad, but sometimes with multiple threads running at once and the thread IDs changing from the time the message is accepted to the time it goes through the filters it's hard to follow. Also, searching several hours/days worth of logs is a pain.

This will accept a directory, time filter, and a search string. All logs in the dir between the times given will be scanned for the search string. Relevant mail threads are output to a specified text file.

=begin
scans through a directory full of SMTP logs and pulls out any threads containing given search string (meant to be used for email addresses and/or domain names)
Follows those threads and outputs to a txt file
Hard-coded to scan logs with extension .log that being with letter s (ex. s20100101123100.log);this can be changed on line 81

designed to read SMTP logs in the format:
200.155.155.001  [1184] 15:41:38 >>> 220 mail.somedomain.com ESMTP SomeServer 10.0.4; Wed, 03 Feb 2010 15:41:38 -0800
200.155.155.001  [1184] 15:41:38 <<< EHLO mail.anotherdomain.com
200.155.155.001  [1184] 15:41:38 >>> 250-mail.somedomain.com Hello mail.anotherdomain.com [200.155.155.001], pleased to meet you.
200.155.155.001  [1184] 15:41:38 <<< MAIL FROM: <noreply@anotherdomain.com> SIZE=90753
etc.
=end
system("cls")
# set the log dir here to meet your needs, be sure to escape your \
logdir = "c:\\scripts\\"
require 'ftools'
require 'time'
# set these up for easier calcs later
mins = 60
hours = 3600
days = 86400
puts "/-----------------/"
puts "/LOG FILE UTILITY /"
puts "/-----------------/"
puts "\n"
puts "Time to search:"
puts "1) Last hour"
puts "2) Last two hours"
puts "3) Since midnight"
puts "4) Last three days"
puts "5) Custom"
puts "\n" 
print "Choose one: "  
STDOUT.flush  
time = gets.chomp  
# BUILD THE TIME FILTER
end_time = Time.new
case time
	when "1" 
		start_time = Time.now - 1 * hours
	when "2"
		start_time = Time.now - 2 * hours
	when "3"
		start_time = 	Time.parse("00:00") 
	when "4"
		start_time = Time.now - 3 * days	
	else
		print "Start date/time (mm-dd-yy tt:tt)? "  
		STDOUT.flush  
		start_time = Time.parse(gets.chomp)	
		print "End date/time (mm-dd-yy tt:tt) [current time]? "  
		STDOUT.flush  
		end_time = Time.parse(gets.chomp)
		if end_time == ""
			end_time = Time.new
		end
end
system("cls")
puts "Searching logs from "
puts "#{start_time } to"
puts end_time
print "\n"
print "Enter your search string: "  
STDOUT.flush  
search = gets.chomp  
# setup the output file. output.txt in the script dir is the default
print "\nEnter output file [output.txt]: "  
STDOUT.flush  
output = gets.chomp  
if output == ""
	output = "output.txt"
end
puts "\n"
d = Dir.new(logdir)
fw = File.open(output, 'w')
# for each file in the logdir
Dir.foreach(logdir)  {
	|x| 
	# only search files with .log extension and starting with an "S"  change this to suit your needs
	if x.slice(-4,4) == ".log" && x.slice(0,1) == "s"
		modtime = File.mtime(logdir + x)	
		#here's our time filter
		if modtime >= start_time && modtime <= end_time then	
			text = File.read(logdir + x)
			thread = ""
			# make sure the log contains the string before we iterate the whole thing
			if text.scan(search).length > 0 then
				fw.puts "/----------------------------------------------------/"		
				fw.puts "/ " + x 
				fw.puts "/----------------------------------------------------/"					
				counter = 0 #line number -1
				# read all lines from the current text file into a big array.  this saves some trouble with .scan later on
				f = IO.readlines(logdir + x)
				while (counter < f.length)
					if f[counter].scan(search).length > 0
						#  we've got a bite!  step back until we find the [THREAD] beginning
						# only move forward if this is a DIFFERENT thread from the one we just ran in the last loop
						if f[counter].scan(/\[[0-9A-Z]{4}\]/)[0] != "[#{thread}]"
							thread = f[counter].scan(/\[[0-9A-Z]{4}\]/)[0]
							thread = thread.slice(1,4)
							# regexp for our thread initiation line
							r1 = Regexp.new('\[(' + thread + ')\].+(Connected)|(MDA)')
							checkline = counter
							until f[checkline].scan(r1).length == 1
								checkline = checkline - 1
							end							
							# move forward, displaying all lines for this thread until we see [THREAD] Disconnected
							r1 = Regexp.new('\[(' + thread + ')\].+(Disconnected)')
							firstone = 0 #sloppy, I know, but eady way to print a "session start" line
							until f[checkline] == nil || f[checkline].scan(r1).length == 1
								r2 = Regexp.new('\[(' + thread + ')\]')
								if f[checkline].scan(r2).length > 0
									if firstone == 0 
										fw.puts "+---START SESSION---+"
										firstone = 1
										mda = ""
									end
									fw.print "#{checkline}: "
									fw.puts f[checkline]
									# check to see if this is the "delivery accepted" (MDA) line.  if it is, follow this thread, as well, for 5 seconds
									r3 = Regexp.new('\[(' + thread + ')\].+(accepted for delivery)')
									if f[checkline].scan(r3).length > 0 
										# store the second mark we're starting on
										thread2 = f[checkline+1].scan(/\[[0-9A-Z]{4}\]/)[0]
										thread2 = thread2.slice(1,4)
										# we only follow this thread for 5 secs max, it doesn't take the mail processor any longer than that to deliver or mark as spam
										thread2_secs = f[checkline+1].scan(/:[0-9]{2}\s/)[0].slice(-3,2).to_i
										# now we've got the 2nd thread (MDA) stored as thread 2, follow it and store results as a string, which we'll print later
										checkmda = checkline
										if thread2_secs > 54
											goal_secs = 0
										else
											goal_secs = thread2_secs + 5
										end
										r4 = Regexp.new('\[(' + thread2 + ')\]')
										while f[checkmda] != nil && thread2_secs != goal_secs
											if f[checkmda].scan(r4).length > 0
												mda = mda + f[checkmda]
											end
											thread2_secs = f[checkmda].scan(/:[0-9]{2}\s/)[0].slice(-3,2).to_i
											checkmda = checkmda + 1
										end
									end
								end
								checkline = checkline + 1
							end	
							# print the last line in our "regular" thread
							fw.print "#{checkline}: "							
							fw.puts f[checkline]
							# print our MDA thread
							fw.puts "#{mda}"
							if firstone == 1
								fw.puts "+---END SESSION---+"
							end 
						end
					end
					counter = counter + 1
				end			
			end
		end
	end
}

Was This Post Helpful? 1
  • +
  • -

#28 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 611
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #5 Challenge: Ruby

Posted 04 February 2010 - 03:08 AM

My eyes!

The above snippet reminds me of a similar example in a Haskell book I once read. The author commented that the example threatened to snake right off the screen.

This post has been edited by Raynes: 04 February 2010 - 07:05 AM

Was This Post Helpful? 0
  • +
  • -

#29 MandyZammit  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 6
  • Joined: 11-December 08

Re: Week #5 Challenge: Ruby

Posted 04 February 2010 - 04:02 AM

me and my student mates have recently used ruby on rails to create a website... www.sportX.tk :D feel free to visit and register :P it will help in our assignment marking :D
Was This Post Helpful? 0
  • +
  • -

#30 njovin  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 6
  • Joined: 31-January 10

Re: Week #5 Challenge: Ruby

Posted 04 February 2010 - 09:12 AM

View PostRaynes, on 04 February 2010 - 02:08 AM, said:

My eyes!

The above snippet reminds me of a similar example in a Haskell book I once read. The author commented that the example threatened to snake right off the screen.


I had the same thought when I previewed the post. I figured it would be better to make it copy-friendly then to adjust everything left and make it less readable.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3