我正在学习嵌套,我的任务是让每个新行以缩进开头。这是我的代码,但它不起作用
$nestingDepth = 0
def logger description, &block
puts "Beginning #{description}".rjust($nestingDepth)
puts $nestingDepth
$nestingDepth = $nestingDepth + 10
result = block.call
$nestingDepth = $nestingDepth - 10
puts $nestingDepth
puts "End of #{description} block that returned #{result}".rjust($nestingDepth)
end
logger "first block" do
logger "second block" do
logger "third block" do
puts "third block part"
end
puts "second block part"
end
puts "first block part"
end
答案 0 :(得分:4)
您的代码有几个问题:
DSL
类。puts
,但是你从未改变它的定义,我看不出你是如何期望它打印一个缩进的字符串,它只是打印字符串而没有缩进。为此,您需要定义一个使用缩进打印的特殊方法,例如: log
rjust
,期望它会缩进字符串。这种方法有不同的目的 - 将一个字符串向右调整(即用左边填充它),并指定长度。如果字符串长于指定的长度,则返回原始字符串。要实际缩进字符串,您应该puts ' ' * nestingDepth + string
。起初看起来很神奇,但*
运算符只是重复字符串,例如'abc' * 3 #=> 'abcabcabc'
全部合在一起我会这样做:
class DSL
def initialize
@depth = 0
end
def logger(description, &block)
log "Beginning #{description}"
@depth += 1
result = instance_eval(&block)
@depth -= 1
log "End of #{description} that returned #{result}"
end
def log(string)
puts indent + string
end
private
def indent
' ' * (10 * @depth)
end
end
def logger(*args, &block)
DSL.new.logger(*args, &block)
end
示例:
logger "first block" do
logger "second block" do
logger "third block" do
log "third block part"
end
log "second block part"
end
log "first block part"
end
打印:
Beginning first block
Beginning second block
Beginning third block
third block part
End of third block that returned
second block part
End of second block that returned
first block part
End of first block that returned
答案 1 :(得分:1)
您的问题是rjust
需要一个大于其应用字符串长度的整数。你的字符串是:
"Beginning #{description}"
变成了:
Beginning first block
Beginning second block
在大多数传递中,这是一个21或22的长度。你所做的最大值$nestingdepth
是20.当整数小于字符串的长度时,它只返回没有填充的字符串。如果我以25的嵌套深度启动脚本,你会看到它展开。
Beginning first block
25
Beginning second block
35
Beginning third block
45