编程打卡:来玩玩Ruby语言吧2.1!
我们前面实现了一个有趣的树类Tree
,但它不具有简洁的用户接口,来设置一棵新树,为它写一个初始化方法,接受散列表和数组嵌套的结构。写好之后,你可以这样设置新树:{'grandpa' => { 'dad' => {'child 1' => {}, 'child 2' => {} }, 'uncle' => {'child 3' => {}, 'child 4' => {} } } }
。
代码实现
class Tree
attr_accessor :children, :node_name
def initialize (tree)
tree.each do
|name,children|
@children = children.map{|name,children| Tree.new(name => children)}
@node_name = name
end
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
ruby_tree = Tree.new({"Ruby" => {"Tim" => {"Dick" => {}},"Doge" => {"Wong" => {"Steve" => {}}}}})
ruby_tree.visit_all {|node| puts node.node_name}
运行结果
Ruby
Tim
Dick
Doge
Wong
Steve
写一个简单的grep程序,把文件中出现某词组的行打印出来,并且显示行号
代码实现
lineNumber = 1
targetWord = ARGV.shift
ARGF.each do
|s|
puts "#{lineNumber}: #{s}" if s.include? targetWord
lineNumber += 1
end
运行结果
ruby main.rb Japanese hello123.txt
176: Japanese: 私はガラスを食べられます。それは私を傷つけません。
标签:node,end,name,visit,2.1,打卡,Ruby,children
From: https://www.cnblogs.com/sugar-refinery/p/17356147.html