? ~_~学习Ruby第三天。主要内容为 Exception、Numeric类、Array类、String类。
??? 1 Exception
puts("-----------------------begin rescue end--------------------") #获取文件的行数、单词数、字节数 ltotal = 0 wtotal = 0 ctotal = 0 ARGV.each{|file| begin input = open(file) l = 0 w = 0 c = 0 while line = input.gets l += 1 c += line.size line.sub!(/^\s+/,"") ary = line.split(/\s+/).size w += ary.size end input.close printf("%8d %8d %8d %s\n",l,w,c,file) ltotal += l ctotal += c wtotal += w rescue => ex print ex.message,"\n" end } printf("%8d %8d %8d %s\n",ltotal,wtotal,ctotal,"total") puts("-----------------------begin rescue ensure end--------------------") #copy操作 def copy(from,to) src = open(from) begin dst = open(to,"w") data = src.read dst.write(data) dst.close rescue ensure src.close end end #read操作 def read(file) begin input = open(file) while line = input.gets print line end rescue ensure input.close end end copy("a.txt","b.txt") read("b.txt") puts "\n" p n = Integer("abc") rescue 0 p n = Integer("1") rescue 0 puts("-----------------------catch throw--------------------") def test_throw throw :test end catch(:test){ puts "aaa" #会输出 test_throw puts "bbb" #不会输出 } catch(:exit){ val = 10 loop{ puts "外层循环" loop{ val -= 1 if val == 0 throw :exit end print "内层循环",val,"\n" } } }
?? Ruby的Exception处理的begin~rescue~ensure~end部分与java的try~catch~finally相似
?? 不同之处在于Ruby的throw、catch有点像goto语句
?
??? 2 Numeric
?
puts("-----------------------Integer--------------------") p 2 ** 1000 #**表示幂乘 puts("-----------------------数值常数-------------------") p 1_23_45 p 0x10 #十六进制 p 010 #八进制 p 0b10 #二进制 p 0d10 #十进制 p 10 #十进制 p 1_234.0e-4 #浮点数 p ?a #a的ASCII码 p ?\t #TAB键的ASCII码 p ?\C-a #Ctrl+a的指令码 puts("-----------------------练习------------------------") def cels2fahr(num) num * 9 / 5.0 + 32 end p cels2fahr(23) #=>73.4 def fahr2cels(num) (num - 32) * 5.0 / 9.0 end p fahr2cels(73.4) #=>23.0 for i in 1..100 printf("%d %f\n",i,fahr2cels(i)) end def dice(m) rand(m) + 1 end p dice(6) def prime?(num) if num == 2 || num ==3 || num == 5 return true end j = Math.sqrt(num).to_i for i in 2..j if num % i ==0 return false end end if i >= j return true end end p prime?(6)
??? Numeric类的架构为 Numeric ->Integer + Float, Integer->Fixnum + Bignum
?
?
?? 3 Array
=begin 2012-5-8 18:08 =end puts("-----------------------建立数组--------------------") a = Array.new p a a = Array.new(5) p a a = Array.new(5,"ruby") p a lang = %w(abc def hi) p lang lang = %w<abc def hi> p lang lang = %w|abc def hi| p lang color_table = {"white" => "#FFF","black" => "#000"} p color_table.to_a p "abc def ghi jkl mno pqr stu".split() puts("----------------------索引的用法---------------------") alpha = ["a","b","c","d","e"] p alpha[2] #检索一个元素 p alpha[2..4] #检索多个连续元素 p alpha[2,3] #检索多个连续元素 alpha[2] = "z" #修改一个元素 p alpha alpha[2..4] = ["x","y","z"] #修改多个连续元素 p alpha alpha[2,3] = ["X","Y","Z"] #修改多个连续元素 p alpha alpha[2,0] = ["A","B","C"] #插入元素 p alpha alpha = %W(a b c d e f) p alpha.values_at(1,3,5) #多个索引建立数组 puts("--------------------集合操作数组-----------------------") set01 = [1,2,3,4,5] set02 = [1,2,3] p set01 & set02 #集合交集 p set01 | set02 #集合并集 p set01 - set02 #集合差 p set01 + set02 #集合连接 puts("-------------------list操作数组------------------------") stack = [1,2,3,4,5] p stack.push(6) p stack.pop p stack.last p stack.unshift(0) p stack.shift p stack.first puts("------------------数组主要方法-------------------------") =begin 数据加入数组 =end a = [1,2,3,4,5] a.unshift(0) #前端加入元素 p a a.push(6) #后端加入元素 p a a << 6 p a a.concat([7,8]) #连接两个数组 破坏性方法 p a p a + [7,8] #连接两个数组 非破坏性方法 a[0..2] = 9 p a a[0..2] = [1,2] p a =begin 删除数组元素 =end a = [1,nil,2,nil,3,4,5] b = a a.compact! #破坏性方法 p a p b a = [1,nil,2,nil,3,4,5] #非破坏性方法 b = a p a.compact p b a = [1,2,3,3,4] a.delete(3) p a a.delete_at(2) p a a.delete_if{|item| item >= 2 } p a a = [1,2,3,4] a.slice!(0,2) p a a = [1,2,3,2,2] a.uniq! p a a = [1,2,3,4] a.shift p a a.pop p a =begin 替换数组元素 =end a = [1,2,3,4,5] p a a.collect!{|item| item * 2 } p a a.map!{|item| item / 2 } p a a.fill(9,1..3) p a a.fill(8,1,3) p a a.fill(7,1) p a a.fill(0) p a a = [[1,2],[3,[4,5]],6] a.flatten! p a a.reverse! p a a.sort! p a =begin 小心初始化 =end a = Array.new(3,[0,0,0]) a[0][1] = 1 p a #=>[[0, 1, 0], [0, 1, 0], [0, 1, 0]] a = Array.new(3){ [0,0,0] } a[0][1] = 1 p a #=>[[0, 1, 0], [0, 0, 0], [0, 0, 0]] #并行处理多个数组 zip 方法 a1 = [1,2,3] a2 = [11,22,33] a3 = [111,222,333] result = [] a1.zip(a2,a3){|a,b,c| result << a + b + c } p result puts("--------------------练习-------------------------") a = Array.new(100){|index| index + 1 } p a b = a.collect{|item| item * 100 } p b c = a.reject{|item| item % 3 != 0 } p c p a a.reverse! p a a.sort!{|x,y| x <=> y } p a a = a.sort_by{|i| -i } p a a = [1,2,"a",3," "] result = 0 a.each{|item| if Numeric === item result += item end } p result a = Array.new(100){|i| rand(100) + 1 } p a ary = Array.new(100){|i| i + 1 } result = Array.new 10.times{|i| result << ary[(i * 10)..(i * 10 + 9)] } p result puts("-----------------------------") def cal(num1,num2) result = [] num1.size.times{|i| result << num1[i] + num2[i] } return result end def sum_array(num1,num2) if num1.size < num2.size cal(num1,num2) else cal(num2,num1) end end p sum_array([1,2],[3,4,5]) p sum_array([1,2,2,8],[3,4,5]) puts("-----------------------------") def fun(ary) ary_size = ary.size if ary_size % 2 != 0 return false end stack = [] ary.each{|item| if item == "{" || item == "[" stack.push(item) p stack else s = stack.pop if item == "}" && s != "{" || item == "]" && s != "[" return false end end } p stack.size if stack.size == 0 return true else return false end end p fun(["{","}"]) p fun(["{","]","[","}"])
??这部分需要注意的是 破坏性方法 与 非破坏性方法
? 所谓 破坏性方法指的是该方法会改变原来的对象,指向该对象的所有引用调用该对象时已经不再为原来的对象。Ruby中一般方法后面加有!均为破坏性方法。
?? 还有需要注意的是 迭代器部分
Array的迭代器有collect,map(功能与collect一样),each,都是对数组中元素一一进行操作,非下标。
Array.new(100){|i|i + 1}中的i为下标。
?
4 String
?
=begin 字符串操作 =end #建立字符串方法 moji = "字符串" str1 = "这也是#{moji}" #=>"这也是字符串" p str1 str2 = '这也是#{moji}' #=>"这也是#{moji}" p str2 desc = %Q{Ruby "dsds"} p desc str = %q{dds'ds'} p str 10.times{|i| 10.times{|j| print <<"EOB" i: #{i} j: #{j} i * j = #{i * j} EOB } } #使用 Here Document(嵌入文档) print <<"EOB" dsda 12 EOB #获取字符串长度 p "abc".length #返回字节数 p "abc".size #返回字节数 p "中国".split(//e).size #返回文字数 #检查字符串长度是不是0 p "".empty? #true p "foo".empty? #false colum = "This,is,a,big,mistake".split(/,/) p colum p colum.to_s str = "This is a big mistake".unpack("a10a2a*") p str a = "hello" b = "world" c = a a = a + b #建立了新对象 p a #a指向了新的对象 p c #c所指向的对象没有变 a = "hello" b = "world" c = a a << b #并没有建立新对象 p a #a还是指向原有的对象 p c #c也是 str = "abcd" p str[0] p str[0].chr p str[0..2] s = "甲乙丙丁" p s.split(//e)[0] str = "abcd" p str.chop #=>"abc" chop 不管如何都会删除最后一个字符 p str.chomp #=>"abcd"chomp 只会删除行尾的换行字符 str = "abcd\n" p str.chop #=>"abcd" p str.chomp #=>"abcd" begin file = open(ARGV[0]) while line = file.gets line.chomp! print line end rescue ensure file.close end #字符串取代 sub只取代第一次遇到的,gsub全部 str = "aaaaaaaa" p str.sub("aa","12") #=>"12aaaaaa" p str.gsub("aa","12") #=>"12121212" #查找字符串 index从左往右 rindex从右往左 #返回值为首次的下标 str = "ababababcdcd" p str.index("abab") #=>0 p str.rindex("abab") #=>4 #String与Array共有的方法 str = "abc" str[1..3] = "C" p str str = "Hello,Ruby." p str.slice!(-1).chr p str.slice!(5..5) p str.slice!(0,5) p str a = "123" p a + "456" p a p a.concat("78") p a p a.delete!("1289") #delete方法如果参数中含有字符串中没有的字符不会报错 p a p a.reverse str = " aa bb cc " p str.strip! #=>"aa bb cc" str = "Ruby Language" p str.upcase #=>"RUBY LANGUAGE" p str.downcase #=>"ruby language" p str.swapcase #=>"rUBY lANGUAGE" p str.capitalize #=>"Ruby language" #tr方法可以一次性替换多个字符 p "abcdefg".tr("b","B") p "abcdefg".tr("be","BE") p "abcdefg".tr("a-d","A-D") puts("----------------------------练习--------------------") str = "Ruby is an object oritented programming language" p ary = str.split() p ary.sort p ary.sort_by{|i| i.upcase } def begin_upcase(str) ary = str.split() result = "" # str.slice!(0..str.size) ary.collect!{|item| result << item.capitalize << " " } return result.to_s.chop! end p begin_upcase(str) def cal_aph(str) cal = Array.new(55,0) for i in 0..str.size - 1 if " " == str[i].chr cal[0] += 1 elsif ('A'..'Z') === str[i].chr cal[str[i] - 64] += 1 elsif ('a'..'z') === str[i].chr cal[str[i] - 69] += 1 end end for i in 0..54 if cal[i] != 0 if i == 0 print "' ':" elsif i <= 27 print ("'",(i + 64).chr,"':") else print ("'",(i + 69).chr,"':") end cal[i].times{ print("*") } print("\n") end end end cal_aph(str) #不用Numeric提供的方法将"1234"转化为1234 def num2astrisk(str) n = str.size result = 0 for i in 0..n-1 temp = 1 (n - i - 1).times{ temp *= 10 } result += (str[i].to_i - 48) * temp end result.times{ print "*" } return result end p num2astrisk("123") #注意点 =begin str[i]返回的是数值 因此字符转化为数值 可以使用 Integer("1"),也可以减去相应的ascii码值 =end p Integer("2") #=>2
??
String类和Array类?细节问题很多。两者有一些相似的方法,两者可以进行相互的转化。:)