ruby 方法小技巧

1. 让sym 和string 都能访问hash

with_indifferent_access

2. ruby 中的 urlencode 和 urldecode

##1、使用 URI::encode

require 'open-uri'
puts URI::encode 'C#' #输出C%23
puts URI::decode 'C%23' #输出C#
##2、使用 CGI.escape

require 'cgi'
puts CGI.escape 'C#' #输出C%23
puts CGI.unescape 'C%23' #输出C#

3. take 方法

%w(a b c).take(5, "x") # => ["a", "b", "c", "x", "x"] 

4. 单复数转换

require 'active_support/inflector'

puts "user".pluralize #=> users
puts "repositories".singularize #=> repository

 5、 ruby on rails关于字符串中特殊字符处理\n\t\r 的方法   

chomp和chomp!

chop 和chop!

strip和strip!

rstrip和rstrip!

和strip相似 ,只处理右边的后面的空字符或者\t \n \r

lstrip和lstrip!

和strip相似 ,只处理左边的前面的空字符或者\t \n \r

gsub 和 gsub!

字符串的替换,将一串字符串中指定的字符替换成另一个字符

replace

字符串替换

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

  

 

posted @ 2023-06-09 13:33  鞋带松了  阅读(4)  评论(0编辑  收藏  举报