Ruby 随机ASCII字符生成器

require 'enumerator'

def random_string(length=10, s="")
  length.enum_for(:times).inject(s) do |result, index|
    s << rand(93) + 33 
  end
end

Ruby CC国家代码

countries = [
	["",  "Generic",  ["1.0","2.0", "2.5"]],
	["ar%2F", "Argentina",  ["2.5"]],
	["au%2F", "Australia",  ["2.0","2.1"]],
	["at%2F", "Austria",   ["1.0","2.0"]],
	["be%2F", "Belgium",  ["2.0"]],
	["br%2F", "Brazil",  ["2.0", "2.5"]],
	["bg%2F", "Bulgaria",  ["2.5"]],
	["ca%2F", "Canada",  ["2.0","2.5"]],
	["cl%2F", "Chile",  ["2.0"]],
	["hr%2F", "Croatia",  ["2.0","2.5"]],
	["hu%2F", "Hungary",  ["2.5"]],
	["fi%2F", "Finland",  ["1.0"]],
	["fr%2F", "France",  ["2.0"]],
	["de%2F", "Germany",  ["2.0","2.5"]],
	["il%2F", "Israel",  ["1.0"]],
	["it%2F", "Italy",  ["2.0"]],
	["jp%2F", "Japan",  ["2.0", "2.1"]],
	["kr%2F", "Korea",  ["2.0"]],
	["my%2F", "Malaysia",  ["2.5"]],
	["nl%2F", "Netherlands",  ["1.0","2.0", "2.5"]],
	["pl%2F", "Poland",  ["2.0", "2.5"]],
	["si%2F", "Slovenia",  ["2.5"]],
	["za%2F", "South Africa",  ["2.0", "2.5"]],
	["es%2F", "Spain",  ["2.0","2.1", "2.5"]],
	["se%2F", "Sweden",  ["2.5"]],
	["tw%2F", "Taiwan",  ["2.0"]],
	["uk%2F", "UK: England & Wales",  ["2.0"]],
	["scotland%2F", "UK: Scotland",  ["2.5"]]	
]

Ruby 简单的webrick服务器

#!/usr/bin/ruby

require 'webrick'
include WEBrick

def start_webrick(config = {})
  config.update(:Port => 5001)
  server = HTTPServer.new(config)

  yield server if block_given?
  ['INT', 'TERM'].each do |signal|
    trap(signal) { server.shutdown }
  end
  
  server.start
end

start_webrick(:DocumentRoot => 'path-to-document-root',
              :ServerType => Daemon)

Ruby 一个assert_difference

module AssertHelper
  # Author:: http://blog.caboo.se/articles/2006/06/13/a-better-assert_difference
  # 
  # == Examples
  #   assert_difference Group, :count do
  #     post :create, :group => { :name => 'monkeys' }
  #   end
  #   
  #   assert_difference [ User, Group ], :count do
  #     Membership.create(:user_id => 1, :group_id => 5)
  #   end 
  #   
  #   assert_difference User, :name, nil do
  #     post :update, :id => 5, { :name => 'monkeys' }
  #   end
  def assert_difference(objects, method = nil, difference = 1)
    objects = [objects].flatten
    initial_values = objects.inject([]) { |sum,obj| sum << obj.send(method) }
    yield
    if difference.nil?
      objects.each_with_index { |obj,i|
        assert_not_equal initial_values[i], obj.send(method), "#{obj}##{method}"
      }
    else
      objects.each_with_index { |obj,i|
        assert_equal initial_values[i] + difference, obj.send(method), "#{obj}##{method}"
      }
    end
  end
  
  def assert_no_difference_in_size(object, methods = nil, &block)
    assert_difference_in_size object, methods, 0, &block
  end
end

Ruby 简洁案例

unit_of_time =
   case num
   when 0..60:           "second" 
   when 0..60 * 60:      "minute" 
   when 0..60 * 60 * 24: "hour" 
   else                  "day" 
   end

unit_of_time = case
  when num < 60:           "second" 
  when num < 60 * 60:      "minute" 
  when num < 60 * 60 * 24: "hour" 
  else                     "day" 
end

Ruby 简明如果

unit_of_time =
   if num < 60:              "second" 
   elsif num < 60 * 60:      "minute" 
   elsif num < 60 * 60 * 24: "hour" 
   else                      "day" 
   end

Ruby auto_drop_migration.rb

module AutoDropMigration
  module Migration
    # Drop all tables and indexes created by the migration
    #   class AddUser < ActiveRecord::Migration
    #     def self.up
    #       ...
    #     end
    #     
    #     def self.down
    #       drop_created_tables_and_indexes(__FILE__)
    #     end
    #     
    def drop_created_tables_and_indexes(migration)
      File.open(migration) do |fp|
        fp.readlines.reverse.each do |line|
          if line =~ /^\s+add_index\s+(.*)$/
            args = eval("parse_args(#{$1})")
            eval("remove_index #{args[0..1].join(',')}") rescue nil
          elsif line =~ /^\s+add_foreign_key\s+(.*)$/
            eval("remove_foreign_key #{$1}") rescue nil
          elsif line =~ /^\s+create_table\s+:([^,]+)(,.*)$/
            drop_table($1) rescue nil
          end
        end
      end
    end
    
    def parse_args(*s) 
      s
    end
  end
end

ActiveRecord::Migration.extend(AutoDropMigration::Migration)

Ruby 使用Rake作为图书馆

#!/usr/bin/env ruby # -*- ruby -*- exts = ['.rb'] if ARGV[0] =~ /^\.[a-zA-Z0-9]+$/ exts = [] while ARGV[0] =~ /^\.[a-zA-Z0-9]+$/ exts << ARGV.shift end end ext = "{" + exts.join(',') + "}" if ARGV.size < 1 puts "Usage: #{File.basename($0)} [.ext ...] pattern ..." exit 1 end require 'rake' FileList["**/*#{ext}"].egrep(Regexp.new(ARGV.join('|')))

Ruby DayRange

class DayRange SHORT_NAMES = %w[Mon Tue Wed Thu Fri Sat Sun].freeze LONG_NAMES = %w[ Monday Tuesday Wednesday Thursday Friday Saturday Sunday ].freeze def initialize(*days) @days = days.map do |d| ds = d.to_s.downcase.capitalize SHORT_NAMES.index(ds) || LONG_NAMES.index(ds) || d - 1 end rescue raise(ArgumentError, "Unrecognized number format.") unless @days.all? { |d| d.between?(0, 6) } raise ArgumentError, "Days must be between 1 and 7." end raise ArgumentError, "Duplicate days given." unless @days == @days.uniq end def to_s(names = SHORT_NAMES) raise ArgumentError, "Please pass seven day names." unless names.size == 7 @days.inject(Array.new) do |groups, day| if groups.empty? or groups.last.last.succ != day groups << [day] else groups.last << day groups end end.map { |g| g.size > 2 ? "#{g.first}-#{g.last}" : g.join(", ") }. join(", ").gsub(/\d/) { |i| names[i.to_i] } end end

Ruby 我的irbrc

#require 'rubygems'
#require 'wirble'
#Wirble.init
#Wirble.colorize

IRB.conf[:AUTO_INDENT] = true
IRB.conf[:USE_READLINE] = true
IRB.conf[:LOAD_MODULES] = []  unless IRB.conf.key?(:LOAD_MODULES)
unless IRB.conf[:LOAD_MODULES].include?('irb/completion')
  IRB.conf[:LOAD_MODULES] << 'irb/completion'
end

HISTFILE = "~/.irb_history"
MAXHISTSIZE = 100

begin
  if defined? Readline::HISTORY
    histfile = File::expand_path( HISTFILE )
    if File::exists?( histfile )
      lines = IO::readlines( histfile ).collect {|line| line.chomp}
      puts "Read %d saved history commands from %s." %
        [ lines.nitems, histfile ] if $DEBUG || $VERBOSE
      Readline::HISTORY.push( *lines )
    else
      puts "History file '%s' was empty or non-existant." %
        histfile if $DEBUG || $VERBOSE
    end

    Kernel::at_exit {
      lines = Readline::HISTORY.to_a.reverse.uniq.reverse
      lines = lines[ -MAXHISTSIZE, MAXHISTSIZE ] if lines.nitems > MAXHISTSIZE
      $stderr.puts "Saving %d history lines to %s." %
        [ lines.length, histfile ] if $VERBOSE || $DEBUG
      File::open( histfile, File::WRONLY|File::CREAT|File::TRUNC ) {|ofh|
	lines.each {|line| ofh.puts line }
      }
    }
  end
end

puts '.irbc completed'