-
分别找到用代码块和不用代码块读取文件的方法,用代码块有什么好处?
# 未使用代码块 file = File.new("file.txt", "r") while (line = file.gets) puts "#{line}" end file.close # 使用代码块 File.open("file.txt", "r") do |i| while (line = i.gets) puts "#{line}" end end # 包括异常处理 begin File.open("file.txt", "r") do |i| while (line = i.gets) puts "#{line}" end end rescue => err puts "Exception: #{err}" err end # 放入代码块中能减少一外部变量,使文件使用完结束代码块,变量会被回收,文件会自动关闭,不用担心忘记手动关闭文件流
-
如何把散列表转换成数组?数组能转换成散列表吗?
hash.to_a # 将hash转换为数组,其中每个元素是一个key, value组成的数组 h = {'1'=>'a','2'=>'b'} h.to_a # => [["1", "a"], ["2", "b"]] # 当数组元素为偶数个数的时候,奇数时会异常: arr = %w[a b c d] #=> ["a", "b", "c", "d"] h = Hash[*arr] #=> {"a"=>"b", "c"=>"d"} # 数组明明是一维或者多维线性的,散列表是键值对的形式,干嘛这样去转换,实际应用中一般就是散列表的键或者值分别和数组相互转换。
-
你能循环遍历散列表吗?
h = {3=>6, 4=>10, 5=>15} a.each{ |k,v| puts "#{k}"=>"#{v}"} for k in a.keys # h.values p k p a[k] end
-
Ruby的数组能当作栈来用,它还能用作哪些常用的数据结构?
队列 稀疏矩阵
-
有一个数组,包含16个数字。仅用 each 方法打印数组中的内容,一次打印4个数字。然后,用可枚举模块的 each_slice 方法重做一遍。
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] temp = [] arr.each {|i| if 4 == temp.length print temp puts temp = [] else temp.push(i) end } arr.each_slice(4) {|x| p x}
-
我们前面实现了一个有趣的树类 Tree ,但它不具有简洁的用户接口,来设置一棵新树,为它写一个初始化方法,接受散列表和数组嵌套的结构。写好之后,你可以这样设置新树: {‘grandpa’ => { ‘dad’ => {‘child 1’ => {}, ‘child 2’ => {} }, ‘uncle’=> {‘child 3’ => {}, ‘child 4’ => {} } } } 。
class Tree attr_accessor :children, :node_name def initialize(h={}) children = [] h.each {|key,value| child = Tree.new(value) children.push(child) } @node_name = h.keys[0] @children = children end end t = Tree.new({'grandpa' => { 'dad' => {'child 1' => {}, 'child 2' => {} }, 'uncle'=> {'child 3' => {}, 'child 4' => {} } } } ) puts t.node_name puts t.children[0].node_name
-
写一个简单的grep程序,把文件中出现某词组的行全都打印出来。这需要使用简单的正则表达式匹配,并从文件中读取各行。 (这在Ruby中超乎想象地简单。 )如果你愿意的话,还可以加上行号。
begin def grep(filename,m) count = 0 File.open(filename, "r") do |f| while (line = f.gets) re = "#{line}".match(m) count += 1 if re.to_s.length > 0 puts count.to_s + ":" +line end end end end rescue => err puts "Exception: "#{err}" err end grep(ARGV.first,ARGV[1]) # 文件名 及要过滤的字符串