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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值