ruby入门
ruby入门
ruby技巧
字符串转数组
s = "a=1&b=2" a = s.split(/&|=/) #["a", "1", "b", "2"]
数组转为哈希
a = ["a", "1", "b", "2"] #*号可以将数组中的字符串展开 Hash[*a] #{"a"=>"1", "b"=>"2"}
char的ASCII值
#ASCII值转为char 120.chr #char转为ASCII值 'x'[0] #查看字符串的ASCII值 "love".chars.map{|c| c[0]}
字符编码转换
require 'iconv' #conv(to, from, str) Iconv.conv('gb2312', 'utf-8', '中国')
split
'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } #=> ["CAF", " P", "RIFERÔL"]
slice! (*args)
s = 'こんにちは' s.mb_chars.slice!(2..3).to_s #=> "にち" s #=> "こんは"
strip ()
'happy'.strip #=>"happy"
mb_chars
name = 'Claus Müller' name.reverse #=> "rell??M sualC" name.length #=> 13 name.mb_chars.reverse.to_s #=> "rellüM sualC" name.mb_chars.length #=> 12
strftime
DateTime.now.strftime => "2010-10-12T09:51:36+08:00" Date.today.strftime => "2010-10-12"
time
?> Time.now.sec => 39 >> ?> Time.now.min => 55 >> ?> Time.now.hour => 9 >> ?> Time.now.day => 12 >> Time.now.mon => 10 >> ?> Time.now.year => 2010 >> ?> Time.now.wday => 2 >> ?> Time.now.yday => 285
to_a、to_f、to_datetime、to_i、to_s