Ruby Ruby:从Hash中随机选择一个项目

#A. Create a Hash
hash = {:key1 => "item1", :key2 => "item2", :key3 => "item3"}
#B. Return a new array of all the Values from the Hash
items = hash.values
#C. Randomly 
puts items[rand(items.length)]

Ruby Ruby:Web 2.0 Generator

#Web 2.0 Generator
5.times do

letters = { ?v => 'aeiou', ?c => 'bcdfghjklmnpqrstvwxyz'}
#p letters
word = ""
i = 0
'cvcvc'.each_byte do |x|
  #puts x
  source = letters[x]
  #<< concatenates or appends
  word << source[rand(source.length)].chr
end

puts word + '.com'

require 'open-uri'
open("http://whois.net/whois_new.cgi?d=" + word + "&tld=com") {|f|
  @req = f.read
  #puts @req
  #Return the 1st position where the string is matched
  @txt = @req.index("No match")
  #puts @txt
  if @txt.nil?
    puts "Domain is available"
  else
    puts "Sorry - Domain is taken"
  end
    
  }
end

Ruby 使用单向散列技术(SHA1)加密数据库的密码

#A. Import the SHA1 Method
require "digest/sha1"
#B. Encrypt the Password string
@hash_pass = Digest::SHA1.hexdigest('super password')
#C. Display the encrypted password
puts @hash_pass

Ruby 将数组转换为YAML,将YAML加载到数组中

#A. Import the YAML Library
require 'yaml'
#B. Create an array
names = %w[chris sandy josie billy suzie]

#Example 1 : Converting an array into YAML using: to_yaml
yaml_example1 = names.to_yaml
puts yaml_example1

#Example 2: Converting an array into YAML using: dump()
yaml_example2 = YAML::dump(names)
puts yaml_example2

#Example 3: Loading YAML back into an array using: load()
array_example = YAML::load(yamloutput2)
puts array_example

Ruby 打印随机lorem句子

#!/usr/bin/env ruby -wKU

copy_to_use = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec leo tellus, ornare ac, molestie eu, suscipit non, urna. Sed in felis. Vivamus justo dui, tempus vel, blandit sed, placerat sit amet, nunc. Praesent rhoncus quam nec risus. Etiam eu nulla eu sapien ultrices hendrerit. Nulla et metus ac ipsum vulputate varius. Nullam nec mauris nec nulla ornare fermentum. In a libero. Aliquam erat volutpat. Ut ornare. Ut nec libero a metus posuere tincidunt. Sed sed arcu. Maecenas lobortis, massa sit amet convallis eleifend, neque erat commodo sapien, ut varius dolor quam vitae lorem. In tellus. Nam eu dolor. Aliquam erat volutpat. Nulla eu arcu. Mauris dignissim, neque egestas rhoncus feugiat, magna diam varius elit, ut hendrerit diam sapien vel velit. Donec lobortis. Aenean mattis turpis sed odio. Donec suscipit lectus quis felis. In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nam interdum. Nulla facilisi. Donec facilisis. Phasellus tristique. Vestibulum pellentesque felis nec dui. Mauris dolor odio, mollis et, sollicitudin vitae, facilisis sed, enim. Duis velit. Nullam a augue. Aliquam erat volutpat. Aenean ut magna nec dui congue congue. Maecenas sagittis nisl ut neque. Nam facilisis urna sed purus luctus congue. Morbi interdum, ligula non ullamcorper faucibus, purus ipsum fermentum neque, in viverra nisi ante at turpis. Ut molestie gravida sapien. "

sentence = copy_to_use.split(". ")

random_sentence = sentence.sort_by{ rand }

print random_sentence[0] + "."

Ruby 计算小时数

#!/usr/bin/env ruby
text = STDIN.read
lines = text.split("\n")
totalHr = 0
totalMin = 0

i = 1
for line in lines do
  begHr = line[0,2].to_i
  begMin = line[3,2].to_i
  endHr = line[8,2].to_i
  endMin = line[11,2].to_i
  hourage = line[0,13]
  desc = line[14, (line.length - 14)]

if line != ""

  if desc == nil
    desc = " "
  end

  if endHr < begHr
   endHr = endHr + 24
  end

  hoursSpent = endHr - begHr

  if endMin < begMin
    endMin = endMin + 60
    hoursSpent = hoursSpent - 1
  end

  minSpent = endMin - begMin

  puts hourage + " (" + hoursSpent.to_s.rjust(2,'0') + "." + minSpent.to_s.rjust(2,'0') + ") " + desc

  totalHr = totalHr + hoursSpent
  totalMin = totalMin + minSpent

  i += 1
end

end

while totalMin >= 60
  totalMin = totalMin - 60
  totalHr = totalHr + 1
end

puts "\n" + "        TOTAL: " + totalHr.to_s.rjust(2,'0') + "." + totalMin.to_s.rjust(2,'0')

Ruby 基准对象#ergo

require 'benchmark'

# The original implementation by Daniel DeLorme
# http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/256662

class NilClass
   def ergo
     @blackhole ||= Object.new.instance_eval do
       class << self
         for m in public_instance_methods
           undef_method(m.to_sym) unless m =~ /^__.*__$/
         end
       end
       def method_missing(*args); nil; end
       self
     end
     @blackhole unless block_given?
   end
end

class Object
   def ergo
     if block_given?
       yield(self)
     else
       self
     end
   end
end

a,b = [1,2,3], nil
n = 100_000

Benchmark.bm(15) do |x|
  x.report("Original") do
    n.times { a.ergo[0];   b.ergo[0] }
  end

  # Turn to facets implementation
  require 'rubygems'
  require 'facets/nilclass/ergo'

  x.report("Facets") do 
    n.times { a.ergo[0];   b.ergo[0] }
  end

  x.report("Logic operators") do
    n.times { a && a[0];  b && b[0] }
  end
end

Ruby String.capitalize_each_word

class String
  def capitalize_each_word
    (self.split(' ').each {|w| w.capitalize! }).join(' ')
  end
end

Ruby 在读取原子提要时解析HTML

# re-encode html escaped entities when reading atom feeds
def rss_html_parse(content)
  content.gsub!("<","<")
  content.gsub!(">",">")
  content.gsub!("\\","")
  content
end

Ruby 为ruby类添加类方法

# Extend class methods for any ruby class
class NameofClass
  class <<self
	# create class methods below
	def	magic
		#insert your magic code here
	end	
  end
end

# now #magic is available for NameofClass on a class level