专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Ruby/Rails

ruby代码保藏

发布时间:2011-06-29 18:12:38 文章来源:www.iduyao.cn 采编人员:星星草
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

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: