不了解 Ruby ljust/rjust/center 方法 [英] Don't understand Ruby ljust/rjust/center methods

查看:38
本文介绍了不了解 Ruby ljust/rjust/center 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning the nesting and my task is to make each new line start with an indent. Here's my code, but it doesn't work

$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

推荐答案

您的问题是 rjust 需要一个大于它所应用的字符串长度的整数.你的字符串是:

Your issue is that rjust requires an integer greater than the length of the string it's applied on. Your string is:

"Beginning #{description}" 

变成:

Beginning first block
Beginning second block

在大多数过程中,长度为 21 或 22.$nestingdepth 的最大长度为 20.当整数小于字符串的长度时,它只返回字符串没有填充.如果我以 25 的嵌套深度开始脚本,您会看到它展开.

On most passes this is either a length of 21 or 22. The largest you ever make $nestingdepth is 20. When the integer is less than the length of the string it just returns the string with no padding. If I start the script with a nesting depth of 25 you see it unfold.

                             Beginning first block
25
                                      Beginning second block
35
                                                 Beginning third block
45

这篇关于不了解 Ruby ljust/rjust/center 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆