Never been to CodeSnippets 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 (or not, you can keep them private!)

Japanese Alphabets Quiz

This is my first Ruby script. It requires two files, hiragana.rb and katakana.rb (I'm pasting them here as well).

Its purpose is to test your knowledge of two Japanese alphabets, Hiragana and Katakana.

# Japanese Alphabets Quiz, version 1.3 :)

puts "Would you rather test your hiragana (1) or katakana (2) knowledge?"

choose = gets.chomp.to_i

if 
	choose == 1
	puts "OK, hiragana, then!"
	require 'hiragana.rb'
	lang_name = "hiragana"
else
	puts "OK, katakana, then!"
	require 'katakana.rb'
	lang_name = "katakana"
end

$score = 0 

10.times do 

	alphabet = $characters
	
	# Select a random pair of key and value from the given hash
	
	character = alphabet.sort_by{ rand }[0...1] 
	
	# Turn the result into an array
	
	pair = character.shift { |key, value| }
	
	# Get the first array value (was the hash key)
	
	question = pair.first
	
	# Ask the question
	
	puts "Which character is " + question + "?"
	
	# Gets the answer from the user, strip spaces and turn it lowercase to match the hash case anyway
	
	answer = gets.chomp.strip.downcase
	
	# Validate user input
	
	if 
		answer == pair.last
		$score += 1
		puts "Correct! " + question + " is " + pair.last + "."
	else
		puts "Wrong! " + question + " is " + pair.last + "."
	end

end

def grade (points)

	case points
	when (0..3)
		"Bad"
	when (4..6)
		"Average"
	when (7..9)
		"Excellent"
	when (10)
		"Perfect"
	end

end

puts "End of " + lang_name + " quiz. You scored " + $score.to_s + " out of 10."

puts "Your grade is " + grade( $score ) + "."


hiragana.rb
# In this hash we set the basic hiragana characters and their respective phonetic counterparts

$characters = 
	{
	'' => 'a',
	'' => 'i',
	'' => 'u',
	'' => 'e',
	'' => 'o',
	'' => 'ka',
	'' => 'ki',
	'' => 'ku',
	'' => 'ke',
	'' => 'ko',
	'' => 'sa',
	'' => 'si',
	'' => 'su',
	'' => 'se',
	'' => 'so',
	'' => 'ta',
	'' => 'ti',
	'' => 'tu',
	'' => 'te',
	'' => 'to',
	'' => 'na',
	'' => 'ni',
	'' => 'nu',
	'' => 'ne',
	'' => 'no',
	'' => 'ha',
	'' => 'hi',
	'' => 'hu',
	'' => 'he',
	'' => 'ho',
	'' => 'ma',
	'' => 'mi',
	'' => 'mu',
	'' => 'me',
	'' => 'mo',
	'' => 'ya',
	'' => 'yu',
	'' => 'yo',
	'' => 'ra',
	'' => 'ri',
	'' => 'ru',
	'' => 're',
	'' => 'ro',
	'' => 'wa',
	'' => 'wo',
	'' => 'n'
	}


# In this hash we set the basic katakana characters and their respective phonetic counterparts

$characters =
		{
		'' => 'a',
		'' => 'i',
		'' => 'u',
		'' => 'e',
		'' => 'o',
		'' => 'ka',
		'' => 'ki',
		'' => 'ku',
		'' => 'ke',
		'' => 'ko',
		'' => 'sa',
		'' => 'si',
		'' => 'su',
		'' => 'se',
		'' => 'so',
		'' => 'ta',
		'' => 'ti',
		'' => 'tu',
		'' => 'te',
		'' => 'to',
		'' => 'na',
		'' => 'ni',
		'' => 'nu',
		'' => 'ne',
		'' => 'no',
		'' => 'ha',
		'' => 'hi',
		'' => 'hu',
		'' => 'he',
		'' => 'ho',
		'' => 'ma',
		'' => 'mi',
		'' => 'mu',
		'' => 'me',
		'' => 'mo',
		'' => 'ya',
		'' => 'yi',
		'' => 'yu',
		'' => 'yo',
		'' => 'ra',
		'' => 'ri',
		'' => 'ru',
		'' => 're',
		'' => 'ro',
		'' => 'wa',
		'' => 'wy',
		'' => 'wo',
	}

Ruby trim string by word count

def trim_by_words(string,wordcount)
    string.split[0..(wordcount-1)].join(" ") +(string.split.size > wordcount ? "..." : "")
end

Manually transfering records with ActiveRecord

require 'rubygems'
require 'active_record'

class SourceTable < ActiveRecord::Base
  #set_table_name 'any_name'
  self.establish_connection(
    :adapter  => "mysql",
    :host     => "source_host",
    :username => "user",
    #:password => "mypass",
    :database => "source_database"
  )
end

class TargetTable < ActiveRecord::Base
  #set_table_name 'any_name'
  self.establish_connection(
    :adapter  => "mysql",
    :host     => "target_host",
    :username => "user",
    #:password => "mypass",
    :database => "target_database"
  )
end

records = SourceTable.find :all
records.each do |r|
  # transition logic goes here
  # t = TargetTable.new :field_one => 'xyz'
  # t.save
end

convert a number to a currency string

# takes a number and options hash and outputs a string in any currency format
def currencify(number, options={})
  # :currency_before => false puts the currency symbol after the number
  # default format: $12,345,678.90
  options = {:currency_symbol => "$", :delimiter => ",", :decimal_symbol => ".", :currency_before => true}.merge(options)
  
  # split integer and fractional parts 
  int, frac = ("%.2f" % number).split('.')
  # insert the delimiters
  int.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
  
  if options[:currency_before]
    options[:currency_symbol] + int + options[:decimal_symbol] + frac
  else
    int + options[:decimal_symbol] + frac + options[:currency_symbol]
  end
end

Ruby format time

This is directly from http://www.ruby-doc.org/core/classes/Time.html#M000236


%a - The abbreviated weekday name (``Sun'')
%A - The full weekday name (``Sunday'')
%b - The abbreviated month name (``Jan'')
%B - The full month name (``January'')
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (``AM'' or ``PM'')
%S - Second of the minute (00..60)
%U - Week number of the current year,
starting with the first Sunday as the first
day of the first week (00..53)
%W - Week number of the current year,
starting with the first Monday as the first
day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character

t = Time.now
t.strftime("Printed on %m/%d/%Y") #=> "Printed on 04/09/2003"
t.strftime("at %I:%M%p") #=> "at 08:56AM"

Ruby simple SMTP email

By Ian Purton and found at http://jiploo.com/blog/simple-email-send-function-in-ruby/
def send_email(from, from_alias, to, to_alias, subject, message)
	msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
Subject: #{subject}
	
#{message}
END_OF_MESSAGE
	
	Net::SMTP.start('localhost') do |smtp|
		smtp.send_message msg, from, to
	end
end

Ruby string proper case


str = "how are you? are you feeling good?"  
puts str.split(/\s+/).each{ |word| word.capitalize! }.join(' ')  
=> "How Are You? Are You Feeling Good?

Mergesort

Mergesort implemented in Ruby. Because of it's performance not really suitable for productive use. (blog entry)

class Array
  def mergesort(&cmp)
    if cmp == nil
      cmp = lambda { |a, b| a <=> b }
    end
    if size <= 1
      self.dup
    else
       halves = split.map{ |half|
        half.mergesort(&cmp)
      }
      merge(*halves, &cmp)
    end
  end

 
  protected
  def split
    n = (length / 2).floor - 1
    [self[0..n], self[n+1..-1]]
  end

  def merge(first, second, &predicate)
    result = []
    until first.empty? || second.empty?
     if predicate.call(first.first, second.first) <= 0
        result << first.shift
      else
        result << second.shift
      end 
    end
    result.concat(first).concat(second)
  end
end

Stable Sort

Stable sort method for the Array class. Acts like the original sort method and accepts blocks in the same way. (blog entry)

class Array
  def stable_sort
    n = 0
    c = lambda { |x| n+= 1; [x, n]}
    if block_given?
      sort { |a, b|
        yield(c.call(a), c.call(b))        
      }
    else
      sort_by &c
    end
  end
end

Mongrel cluster starting after restart on Ubuntu GG

sudo mkdir /etc/mongrel_cluster
sudo ln -s /mnt/app/ticketsolve/shared/config/mongrel_cluster_new_production.yml /etc/mongrel_cluster/mongrel_cluster_new_production.yml
sudo cp /usr/bin/mongrel_cluster_ctl /etc/init.d/
sudo chmod +x /etc/init.d/mongrel_cluster_ctl
cd /etc/init.d/
sudo /usr/sbin/update-rc.d -f mongrel_cluster_ctl defaults