Created
September 8, 2015 02:47
-
-
Save lazybios/a1881161b2f22688a374 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tree | |
# 定义实例变量,使用attr或attr_accessor关键字,前者定义变量和访问变量的同名getter方法(即只读),后者定义的变量多了同名setter方法(注意这里使用了符号) | |
attr_accessor :children, :node_name | |
# 构造方法(构造方法必须命名为initialize) | |
def initialize(name, children=[]) | |
@node_name = name | |
@children = children | |
end | |
# 遍历所有节点并执行代码块block,注意参数前加一个&表示将代码块作为闭包传递给函数 | |
def visit_all(&block) | |
visit &block | |
children.each {|c| c.visit_all &block} | |
end | |
# 访问一个节点并执行代码块block | |
def visit(&block) | |
block.call self | |
end | |
end | |
ruby_tree = Tree.new("Ruby", | |
[Tree.new("Reia"), | |
Tree.new("MacRuby")]) | |
# 访问一个节点 | |
ruby_tree.visit {|node| puts node.node_name} | |
# 访问整棵树 | |
ruby_tree.visit_all {|node| puts "Node: #{node.node_name}"} | |
==Begin | |
最后再提一下Ruby的命名规范: | |
类采用CamelCase命名法 | |
实例变量(一个对象有一个值)前必须加上@,类变量(一个类有一个值)前必须加上@@ | |
变量和方法名全小写用下划线命名法,如underscore_style | |
常量采用全大写下划线命名法,如ALL_CAPS_STYLE | |
用于逻辑测试的函数和方法一般要加上问号,如if test? | |
==End |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment