Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
ruby
puts "Hello World!"
$stdout<<"Hello World!"

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
ruby
gem 'uri-query_params'
require 'uri/query_params'

url = URI("http://myserver.com/custinfo/edit.php?mode=view&fname=Ron%20&%20Jean&lname=Smith")
url.query_params['fname']
# => "Ron & Jean"
url = "http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith"
url = URI.parse(URI.encode(url))

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
ruby
str = "The quick brown fox jumps over the lazy dog. " * 10
outarr = str.scan(/[^ ].{0,76}/)
outarr.each{ |line| puts "> %s" % line }

write a recursive c function to compute gcd(x,y).

ruby
27.gcd(18)
def gcd(x, y)
if x.zero? then y else gcd(y % x, x) end
end

Define a string containing special characters

Define the literal string "\#{'}${"}/"
ruby
special = '\#{\'}${"}/'

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
ruby
text = <<"HERE"
This
Is
A
Multiline
String
HERE
text = "This\nIs\nA\nMultiline\nString"

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
ruby
puts "#{a}+#{b}=#{a+b}"
puts "#{a}+#{b}=%s" % (a + b)

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
ruby
puts "reverse me".reverse

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
ruby
reversed = text.split.reverse.join(' ')

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
ruby
prefix = "> "
string = "The quick brown fox jumps over the lazy dog. " * 10
width = 78
realwidth = width - prefix.length
print string.gsub(/(.{1,#{realwidth}})(?: +|$)\n?|(.{#{realwidth}})/, "#{prefix}\\1\\2\n")
# the same output is achieved with:
puts ("The quick brown fox jumps over the lazy dog. " * 10).gsub(/(.{1,70})(\s+|\Z)/, "> \\1\n")
# however
# "> The quick brown fox jumps over the lazy dog. The quick brown fox jumps".size => 72
# "> over the lazy dog. The quick brown fox jumps over the lazy dog. The".size + "quick".size # first line + first word of second line => 74
# where does 78 come from?

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
ruby
puts " hello ".strip
" hello ".strip!

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
ruby
rot13 = "Hello World #123".tr!("A-Za-z", "N-ZA-Mn-za-m")
rot47 = "Hello World #123".tr!("\x21-\x7e", "\x50-\x7e\x21-\x4f")

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
ruby
uppper = text.upcase

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
ruby
"Caps ARE overRated".downcase

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
ruby
caps = text.gsub(/\w+/) { $&.capitalize }
caps = text.split.each{|i| i.capitalize!}.join(' ')
text.split.map(&:capitalize) * ' '

Find the distance between two points

ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
ruby
42.to_s.rjust(8,"0")
"%08d" % 42

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
ruby
1024.to_s.ljust(6)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
ruby
(7.0/8.0*100).round/100.0
(7.0/8.0).round(2)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
ruby
73.to_s.rjust(10)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
ruby
randomInt = rand(200-100+1)+100;
rand(100..200)

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
ruby
srand(12345)
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
ruby
puts "ok" if ("Hello"=~/^[A-Z][a-z]+$/)

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
ruby
puts $1 if "one two three"=~/^one (.*) three$/

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
ruby
puts "ok" if (text=~/\d+/)

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
ruby
list = text.scan(/\((\w+)\):(\d+)/).collect{|x| x.join}
list=[]
text.scan(/\((\w+)\):(\d+)/) {
list << $1+$2
}

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
ruby
p "Red Green Blue".sub(/e/,'*')

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
ruby
replaced = text.gsub(/se\w+/,"X")

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
ruby
"The {Quick} Brown {Fox}".gsub(/\{(\w+)\}/) {|s| s[1..-2].reverse }

Define an empty list

Assign the variable "list" to a list with no elements
ruby
list = []
list = Array.new

Define a static list

Define the list [One, Two, Three, Four, Five]
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list = %w(One Two Three Four Five)

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
ruby
string = fruit.join(', ')

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
ruby
def join(arr)
return '' if not arr
case arr.size
when 0 then ''
when 1 then arr[0]
when 2 then arr.join(' and ')
else arr[0..-2].join(', ') + ', and ' + arr[-1]
end
end

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
ruby
common = [] ; [4, 5].each {|n| ['a', 'b', 'c'].each {|l| common << [l, n]}}
[4, 5].product(['a', 'b', 'c']).map(&:reverse)

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
ruby
foo = ['andrew', 'bob', 'chris', 'bob']
foo.inject({}) {|h,v| h[v]=h[v].to_i+1; h}.reject{|k,v| v==1}.keys
xs = ['andrew', 'bob', 'chris', 'bob']
xs.uniq.select { |x| xs.count(x) > 1 }

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
ruby
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]
['One', 'Two', 'Three', 'Four', 'Five'].fetch(2)
list = ['One', 'Two', 'Three', 'Four', 'Five']
list.at(2)
['One', 'Two', 'Three', 'Four', 'Five'][2] # <= note the [2] at end of array

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
ruby
['Red', 'Green', 'Blue'][-1]
['Red', 'Green', 'Blue'].at(-1)
['Red', 'Green', 'Blue'].last
['Red', 'Green', 'Blue'].fetch(-1)

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
ruby
common = (beans.intersection(colors)).to_a
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']
common = beans & colors

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
ruby
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
p ages.uniq
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]
ages.uniq!
p ages
ages = (Set.new [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]).to_a
p ages

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
ruby
['Apple', 'Banana', 'Carrot'].shift
fruit.delete_at(0)

Remove the last element of a list

ruby
list = ['Apple', 'Banana', 'Carrot']
list.delete_at(-1)
list = ['Apple', 'Banana', 'Carrot']
list.pop

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
ruby
items = ["apple", "orange", "grapes", "bananas"]
items << first = items.shift

# items is rotated
# first contains the first value in the list
fruits = ["apple", "orange", "grapes", "bananas"]
fruits.rotate!

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
ruby
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]

result = first.zip(last, years)
first = ['Bruce', 'Tommy Lee', 'Bruce']; last = ['Willis', 'Jones', 'Lee']; years = [1955, 1946, 1940]

result = [first, last, years].transpose

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
ruby
suites.each {|s| faces.each {|f| cards << [s, f]}}
puts "Deck %s \'Ace of Hearts\'" % if cards.include?(['h', 'A']) then "contains" else "does not contain" end
suites = ['H', 'D', 'C', 'S']
faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']

deck = suites.product(faces)

puts deck.length #=> 52
puts deck.include?(['H', 'A']) #=> true

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
ruby
["ox", "cat", "deer", "whale"].map{|i| i.length}

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
ruby
now=Time.now
things=["hello", 25, 3.14, now]

numbers=things.select{|i| i.is_a? Numeric}
others=things-numbers
now=Time.now
things=["hello", 25, 3.14, now]

numbers, others=things.partition{|i| i.is_a? Numeric}

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
ruby
[2, 3, 4].all? { |x| x > 1 }

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
ruby
[2, 3, 4].any? { |x| x > 3 }

Define an empty map

ruby
map = {}

Define an unmodifiable empty map

ruby
map = {}.freeze

Define an initial map

Define the map {circle:1, triangle:3, square:4}
ruby
shapes = {'circle'=>1, 'triangle'=>3, 'square'=>4}
shapes = Hash['circle', 1, 'triangle', 3, 'square', 4]
shapes = { :circle => 1, :triangle => 3, :square => 4 }

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
ruby
puts "ok" if map.has_key?('mary')
puts "ok" if map['mary'] # Only works if map entry can't be nil or false

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
ruby
puts map['joe']

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
ruby
pets['rob']='dog'

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
ruby
puts map.delete :bill

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list = %w{a b a c b b}

histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end

p histogram # => {"a"=>2, "b"=>3, "c"=>1}
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
lengths = list.group_by {|x| x.size}
list.inject({}) { |h,x| (h[x.size]||=[]) << x; h }

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
ruby
if (name=='Bob')
puts "Hello, Bob!"
end
puts "Hello, Bob!" if name=='Bob'

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
ruby
if (age > 42)
puts "You are old"
else
puts "You are young"
end
puts (age>42) ? "You are old" : "You are young"
puts "You are #{age > 42 ? "old" : "young"}"

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

ruby
if age > 84
puts "You are really ancient"
elsif age > 30
puts "You are middle-aged"
else
puts "You are young"
end
case
when age > 84 then puts "You are really ancient"
when age > 30 then puts "You are middle-aged"
else puts "You are young"
end

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
ruby
def suffixed(number)
last_digit = number.to_s[-1..-1].to_i
suffix = case last_digit
when 1 then 'st'
when 2 then 'nd'
when 3 then 'rd'
else 'th'
end
suffix = 'th' if (11..13).include?(number)
"#{number}#{suffix}"
end

(1..40).each {|n| puts suffixed(n) }

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
ruby
x=1
while x < 150
puts x
x <<= 1
end

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
ruby
# Ruby has no DO..WHILE construct. Need to write it as a WHILE
rnd = 0
while (rnd != 6)
rnd = rand(6)+1
print rnd
print "," if (rnd!=6)
end
begin
rnd = rand(6)+1
print rnd
print "," if rnd!=6
end while rnd != 6
# This uses Enumerators, ad it becomes almost functional style...

games = Enumerator.new do |yielder|
yielder.yield rand(6) + 1 while true
end

puts games.take_while {|roll| roll != 6}.join(",")

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
ruby
puts "Hello"*5
5.times { print "Hello" }

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
ruby
10.downto(1) { |n| print n, " .. " }
puts "Liftoff!"

Read the contents of a file into a string

ruby
file = File.new("Solution108.rb")
whole_file = file.read

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{line}
}

Write a string to a file

ruby
File.new("a_file", "w") << "some text"
IO.write("file.txt", "some text that overwrites")

Append to a file

ruby
file = File.new('/tmp/test.txt', 'a+') ; file.puts 'This line appended to file!!' ; file.close()

Process each file in a directory

ruby
directory = '/tmp' ; Dir.foreach(directory) {|file| puts "#{file}"}

Process each file in a directory recursively

ruby
def procdir(dirname)
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
puts "DIRECTORY: #{dirpath}" ; procdir(dirpath)
end
else
puts "FILE: #{dirpath}"
end
end
end

# ------

procdir('/tmp')

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
ruby
# With timezone info
puts Time.parse('2008-05-06 13:29')

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
ruby
require 'date'

next_week = Date.today + 8

puts next_week.day # day of month
puts next_week.yday # day of year
puts next_week.strftime('%B') # month name
puts next_week.strftime('%A') # day name

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
ruby
puts DateTime.now
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
ruby
class Greeter
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

(Greeter.new("world")).greet()

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
ruby
class Greeter
attr_accessor :whom
def initialize(whom) @whom = whom end
def greet() puts "Hello, #{@whom}!" end
end

greeter = Greeter.new("world") ; greeter.greet()

greeter.whom = 'Tommy' ; greeter.greet()
puts "I have just greeted %s" % greeter.whom

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
ruby
class Shape
def initialize(name="") @name = name end
end

class Circle < Shape
def initialize(radius) super("circle") ; @radius = radius end

def area() 3.14159 * @radius * @radius end
def circumference() 2 * 3.14159 * @radius end

def print()
puts "I am a #{@name} with ->"
puts "Radius: %.2f" % @radius
puts "Area: %.2f" % self.area()
puts "Circumference: %.2f\n" % self.circumference()
end

end

class Rectangle < Shape
def initialize(length, breadth) super("rectangle") ; @length = length ; @breadth = breadth end

def area() @length * @breadth end
def perimeter() 2 * @length + 2 * @breadth end

def print()
puts "I am a #{@name} with ->"
printf("Length, Width: %.2f, %.2f\n", @length, @breadth)
puts "Area: %.2f" % self.area()
puts "Perimeter: %.2f\n" % self.perimeter()
end
end

# ------

shapes = [Circle.new(4.2), Rectangle.new(2.7, 3.1), Rectangle.new(6.2, 2.6), Circle.new(17.3)]
shapes.each {|shape| shape.print}

Implement and use an Interface

Create a Serializable interface consisting of 'save' and 'restore' methods, each of which:

* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types 'int' and 'string')

Next, create a Person class which has 'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
ruby
class Person
def initialize(name, age)
@name, @age = name, age
end
end

tom = Person.new("Tom Bones", 23)

File.open('tommy.dump', 'w+') {|f| f.write(Marshal.dump(tommy)) }
toms_clone = Marshal.load(File.read('tommy.dump'))

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
ruby
Net::HTTP.start(URL, 80) do |http|
status = if http.get('/').body =~ /#{SRCHEXP}/ then "offers" else "does not offer" end
puts "http:\/\/#{URL} #{status} #{LANGUAGE}"
end

Send an email

Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be, "Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
ruby
require 'net/smtp'
require 'webrick/utils'

body = <<END_OF_MESSAGE
This is a message from langref.org
END_OF_MESSAGE

SMTPSRV = 'smtp.somewhere.com'
USER = 'me' ; DOMAIN = 'somewhere.com' ; FROM = USER + '@' + DOMAIN
TO = 'dest@somewhereelse.com'
SUBJECT = 'Greetings from langref.org'
DATE = Time.now.rfc2822()
MSGID = '<' + WEBrick::Utils.random_string(21) + '.' + WEBrick::Utils.random_string(21) + '@' + SMTPSRV + '>'

Net::SMTP.start(SMTPSRV, 25) do |smtp|
smtp.open_message_stream(FROM, [TO]) do |msg|
msg.puts "From: #{FROM}"
msg.puts "To: #{TO}"
msg.puts "Subject: #{SUBJECT}"
msg.puts "Date: #{DATE}"
msg.puts "Message-ID: #{MSGID}"
msg.puts
msg.puts body
end
end
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
ruby
#!/usr/bin/env ruby

# needed to parse xml
require 'rexml/document'

# grab the file
file = File.new('shop.xml')

# load it as an xml document
doc = REXML::Document.new(file)

# initialize the total to 0 as a float
total = 0.0

# cycle through the items
doc.elements.each('shopping/item') do |item|

# add the price to the total
total += item.attributes['price'].to_f
end

# round the total to the nearest 0.01
total = (total*100.0).round/100.0

# pad the output with the proper number of trailing 0's
printf "$%.2f\n", total

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
ruby
# gem install builder
require 'builder'

xml = Builder::XmlMarkup.new
xml.shopping do
xml.item(:name => "bread", :quantity => 3, :price => "2.50")
xml.item(:name => "milk", :quantity => 2, :price => "3.50")
end
xml

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
ruby
results=[]

1.upto(20) do |a|
1.upto(20) do |b|
c=Math.sqrt(a**2+b**2)
results<<[a, b, c.to_i] if c.to_i==c && !results.index([b, a, c.to_i])
end
end

results=results.sort_by{|r| r[2]}

puts results
def find_pythag( max=20 )
r = []
1.upto max do |n|
n.upto max do |m|
h = Math.sqrt( n**2 + m**2)
r << [n,m,h.to_i] if (h.round - h).zero?
end
end
r.sort_by { |a| a[2] }
end

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

ruby
135.gcd(30)
# => 15
Fun

produces a copy of its own source code

In computing, a quine is a computer program which produces a copy of its own source code as its only output.
ruby
eval s=%q(puts"eval s=%q(#{s})")
x="x=%p;puts x%%x";puts x%x

Subdivide A Problem To A Pool Of Workers (No Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.

Example:

-Input-

(In python syntax)

["ab", "we", "tfe", "aoj"]

In other words, a list of random strings.

-Output-

(In python syntax)

[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...

In other words, all possible permutations of each input string are computed.
ruby
array, threads, answers = ["ab", "we", "tfe", "aoj"], [], []
array.each { |word|
threads << Thread.new(word.split '' ) do |x|
answer = []
x.each { |a|
answer << a
x.each { |b| answer << [a, b].join }
}
answers << answer
end
}
threads.each {|thr| thr.join}
answers

Create a multithreaded "Hello World"

Create a program which outputs the string "Hello World" to the console, multiple times, using separate threads or processes.

Example:

-Output-

Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!

-Notice that the threads can print in any order.
ruby
%w[one two three four].each do |number|
Thread.new(number) { |number|
puts "Thread #{number} says Hello World!"
}.join
end