我有一个Builder类,可以让你添加一个实例变量:
class Builder
def initialize
@lines = []
end
def lines
block_given? ? yield(self) : @lines
end
def add_line( text )
@lines << text
end
end
现在,我该如何更改
my_builder = Builder.new
my_builder.lines { |b|
b.add_line "foo"
b.add_line "bar"
}
p my_builder.lines # => ["foo", "bar"]
进入这个?
my_builder = Builder.new
my_builder.lines {
add_line "foo"
add_line "bar"
}
p my_builder.lines # => ["foo", "bar"]
答案 0 :(得分:12)
class Builder
def initialize
@lines = []
end
def lines(&block)
block_given? ? instance_eval(&block) : @lines
end
def add_line( text )
@lines << text
end
end
my_builder = Builder.new
my_builder.lines {
add_line "foo"
add_line "bar"
}
p my_builder.lines # => ["foo", "bar"]
答案 1 :(得分:1)
您也可以使用ary的参数长度在ruby最佳实践中使用方法:
class Foo
attr_accessor :list
def initialize
@list=[]
end
def bar(&blk)
blk.arity>0 ? blk.call(self) : instance_eval(&blk)
end
端
X = Foo.new
x.bar做 list&lt;&lt; 1 list&lt;&lt; 2 list&lt;&lt; 3 端
x.bar do | foo | foo.list&lt;&lt; 4 foo.list&lt;&lt;五 foo.list&lt;&lt; 6 端
将x.list.inspect
放入