gpt4 book ai didi

ruby - 不懂 Ruby ljust/rjust/center 方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:39 26 4
gpt4 key购买 nike

我正在学习嵌套,我的任务是让每一行都以缩进开头。这是我的代码,但它不起作用

$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

最佳答案

您的代码有几个问题:

  • 您正在使用全局变量,这通常不是一个好主意,请将其作为参数传递下去。为此,您可以使用定义记录器和记录方法的 DSL 类。
  • 您在 block 内调用 puts,但您从未更改它的定义,我不明白您期望它如何打印缩进字符串,它只会正常打印字符串没有缩进。为此,您需要定义一个特殊的方法来打印缩进,例如日志
  • 您正在调用 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

关于ruby - 不懂 Ruby ljust/rjust/center 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27842115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com