首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > Ruby Rails >

ruby代码保藏

2012-12-21 
ruby代码收藏1.sed split file:# return file indexdef sed_split_file(filename)? len 200000? lines

ruby代码收藏

1.sed split file:
# return file index
def sed_split_file(filename)
? len = 200000
? lines = `wc -l #{filename} | awk '{print $1}'`.strip.to_i
? start_at = 1
? end_at = len
? i = 1

? while end_at < lines do
??? cmd = "sed -n '#{start_at},#{end_at}p' #{filename} > #{filename}_#{i}.csv &"
??? `#{cmd}`
??? start_at = end_at + 1
??? end_at = end_at + len
??? i += 1
? end
? i
end

2. ?? .irbrc
#.irbrc

require 'rubygems'
require 'wirble'
Wirble.init
Wirble.colorize
require 'pp'
require 'ap'

class Object
? def local_methods
??? (methods - Object.instance_methods).sort
? end
end

if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')
? require 'logger'
? RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
end

获取平台信息
ruby -e "puts RUBY_PLATFORM"


3.计 算文件行数
require 'find'
dir = "/Users/holin/Downloads/Applications"
arr = []
Find.find(dir) do |path|
? if FileTest.file?(path) && path =~ /results_/
??? arr << (`wc -l #{path} | awk '{print $1}'`.strip.to_i - 1)
? end
end
puts arr.inject(0){|sum, n| sum += n}

4.合并文件
require 'find'
dir = "/Users/holin/Downloads/Applications"
Dir.chdir(dir)
arr = []
Find.find(dir) do |path|
? if FileTest.file?(path) && path =~ /results_/
??? arr << File.read(path).strip
? end
end

File.open("results_all.csv", "w") do |f|
? f.write arr.join("")
end

String to Class Object:
"note".camelcase.constantize


5.Ruby Grep
[1,10,100,1000].grep(1..100) # => [1, 10]
[1,'a',2,'b'].grep(Integer) # => [1,2]

['hello.rb','world.rb','public.html'].select{|x|x=~/\.rb/}.map{|x|x[0..-4]}
['hello.rb','world.rb','public.html'].grep(/(.*)\.rb/){$1}

['a','1','b','2'].select{|x| /^\d*$/ === x}.map{|x| x.to_i}
['a','1','b','2'].grep(/^\d*$/){|x| x.to_i}

['a','1','b','2'].select{|x| /^\d*$/ === x}.map(&:to_i)
['a','1','b','2'].grep(/^\d*$/,&:to_i)
Conclusion: Although the definition and implementation of the “grep” method from Enumerable module is simple, but by combing with other Ruby expression like case equal(“===”), Regexp, and “&symbol” block, It become a very handy and powerful method. Therefore next time when you come across some situation need to use “select + map”, keep “grep” in your mind beforehand.


6.all? and any?
%w{ ant bear cat}.all? {|word| word.length >= 3} #=> true
%w{ ant bear cat}.all? {|word| word.length >= 4} #=> false
[ nil, true, 99 ].all??????????????????????????? #=> false

%w{ ant bear cat}.any? {|word| word.length >= 3} #=> true
%w{ ant bear cat}.any? {|word| word.length >= 4} #=> true
[ nil, true, 99 ].any??????????????????????????? #=> true

7.retrieve the last return:
$ irb
>> 2*3
=> 6
>> _ + 7
=> 13
>> _
=> 13

8.转码:
require 'iconv'
require 'htmlentities'
coder = HTMLEntities.new
result = Iconv.iconv("GBK//IGNORE","UTF8//IGNORE",coder.decode(""))

String to unicode
class String
? def to_json(options = nil) #:nodoc:
??? json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
????? ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
??? }
??? json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
??? json.gsub(/([\xC0-\xDF][\x80-\xBF]|
???????????? [\xE0-\xEF][\x80-\xBF]{2}|
???????????? [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
????? s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&')
??? } + '"'
? end
end

热点排行