Ruby 我的.railsrc

require 'logger'
Object.const_set(:RAILS_DEFAULT_LOGGER, Logger.new(STDOUT))
  
def sql(query)
  ActiveRecord::Base.connection.select_all(query)
end

def loud_logger
  set_logger_to Logger.new(STDOUT)
end

def quiet_logger
  set_logger_to nil
end

def set_logger_to(logger)
  ActiveRecord::Base.logger = logger
  ActiveRecord::Base.clear_active_connections!
end

def define_model_find_shortcuts
  model_files = Dir.glob("app/models/**/*.rb" )
  table_names = model_files.map { |f| File.basename(f).split('.' )[0..-2].join }
  table_names.each do |table_name|
    Object.instance_eval do
      define_method(table_name) do |*args|
        table_name.camelize.constantize.send(:find, *args)
      end
    end
  end
end

IRB.conf[:IRB_RC] = Proc.new { define_model_find_shortcuts }

Ruby 毕达哥拉斯三倍体发电机

#!/bin/ruby
# author: Lukasz Korecki, student no: 0617836
# purpose: simple program generating Pythagorian triples

# Vars:
given_number = 60

m = 1
# Number definitions using the article from wikipedia:
# http://en.wikipedia.org/wiki/Pythagorean_triple#Other_formulas_for_generating_triples
#
a = m*2 + 1
b = (m*2) * (m + 1)
c = ((m*2) * (m + 1)) + 1
sum = a + b + c


# Output and formatting
sep = "\t|\t"
puts "Your max value is " + given_number.to_s
puts sep+"small"+sep+"medium"+sep+"large"+ sep + "sum" + sep
puts "-" * 80

# Main loop calculating the numbers and outputs
while c < given_number
		m +=1
		puts sep + a.to_s +  sep+ b.to_s + sep +c.to_s + sep + sum.to_s + sep

		a = m*2 + 1
		b = (m*2) * (m + 1)
		c = ((m*2) * (m + 1)) + 1
		sum = a + b +c

end

Ruby 向Option Helpers添加Include Blank参数

module ActionView::Helpers::FormOptionsHelper
         
   def options_for_select_with_include_blank(container, selected = nil, include_blank = false)
      options = options_for_select_without_include_blank(container, selected)
      if include_blank
         options = "<option value=\"\">#{include_blank if include_blank.kind_of?(String)}</option>\n" + options
      end
      options
   end
   alias_method_chain :options_for_select, :include_blank
   
   def options_from_collection_for_select_with_include_blank(collection, value_method, text_method, selected = nil, include_blank = false)
      options = options_from_collection_for_select_without_include_blank(collection, value_method, text_method, selected)
      if include_blank
         options = "<option value=\"\">#{include_blank if include_blank.kind_of?(String)}</option>\n" + options
      end
      options
   end
   alias_method_chain :options_from_collection_for_select, :include_blank
   
end

Ruby 列出目录并创建wget调用以构建独立的html目录

dir ="path/to/files"
Dir.new(dir).entries.each { |e| 
  dirname = e.split(".")
  puts "wget -nd -k -r -P#{dirname[0]} http://localhost/path/to/dirs/#{e}"
}

Ruby 在Ruby中设置CPU亲和力

require 'rubygems'
require 'inline'

# By Peter Cooper - http://www.rubyinside.com/
# Oodles of inspiration and examples from
# http://www-128.ibm.com/developerworks/linux/library/l-affinity.html

class LinuxScheduler
  inline do |builder|
    builder.include '<sched.h>'
    builder.include '<stdio.h>'
    builder.c '
      int _set_affinity(int cpu_id) {
        cpu_set_t mask;
        __CPU_ZERO(&mask);
        __CPU_SET(cpu_id, &mask);
        if(sched_setaffinity(getpid(), sizeof(mask), &mask ) == -1) {
          printf("WARNING: Could not set CPU Affinity, continuing as-is\n");
          return 0;
        }
        return 1;
      }
    '
  end

  # cpu_id is 0-based, so for core/cpu 1 = 0, etc..
  def self.set_affinity(cpu_id)
    self.new._set_affinity(cpu_id.to_i)
  end
end


# Set this process's CPU affinity
LinuxScheduler.set_affinity(ARGV.first)

# Hog up all the CPU time on that processor
1000000.times { b = rand(100) ** 100 }

Ruby CGI图书馆了

#yes
require 'cgi'

#no
require 'CGI'

Ruby '未初始化的恒定Gem :: GemRunner'

# add to /usr/bin/gem
require 'rubygems/gem_runner'

Ruby 执行具有不同级别的错误消息传递的任意代码

def silently(&block)
  warn_level = $VERBOSE
  $VERBOSE = nil
  result = block.call
  $VERBOSE = warn_level
  result
end

# e.g.
silently { require 'net/https' }

Ruby 使Ruby字符串的行为与文件类似

require 'stringio'

sio=StringIO.new('acts like a file')
puts sio.pos # => 0
sio.pos= sio.length - 4
puts sio.read # => 'file'

Ruby 通过避免字符串累积来优化Ruby内存使用

"The lessons here are:

   1. Temporary strings and temporary objects will stockpile. Just because you leave a method doesn't mean they are gone....
   2. Arrays, hashes, objects are memory cheap. Worry about your strings. Do you have string corpses everywhere?
   3. Build your object from all the pieces, avoiding temporary objects as much as possible. Then, when you're done with it, toss the big object out of scope at once!"