【发布时间】:2017-01-31 11:02:55
【问题描述】:
我正在尝试使用名为“bar”的子项创建一个“foo”项。预期的输出是:
foo_item = Item @name="foo", @children=[<...>]
foo_item children = [Item @name="bar", @children=[]]
我正在使用块、绑定和评估。这是我的代码:
class Item
attr_accessor :name, :children
def initialize name
@name = name
@children = []
end
end
def item(item_name)
@item = Item.new(item_name)
if @context
@context.eval('@item.children') << @item
end
if block_given?
old_context = @context if @context
@context = binding
yield
if old_context
@context = old_context
else
@context = nil
end
end
@item
end
foo_item = item('foo') do
item('bar')
end
puts "foo_item = #{foo_item.inspect}"
puts "foo_item children = #{foo_item.children.inspect}"
在下面的实际输出中,foo_item 包含 bar 项,其子项也是 bar 项:
foo_item = Item @name="bar", @children=[<...>]
foo_item children = [Item @name="bar", @children=[<...>]]
给定相同的输入:
foo_item = item('foo') do
item('bar')
end
如何获得上述预期输出?
【问题讨论】:
标签: ruby dependency-injection eval metaprogramming