Raku 中的 gist 方法

What does gist do in Raku

当你打印对象的时候, 例如 say $x, Raku 调用 gist 方法. 这个方法是为所有内建类型定义的:对于其中一些类型,它调用 Str 方法,对于某些类型它调用 perl 方法,对于某些类型,它使字符串表示有所不同。

让我们看看如何使用该方法来创建您自己的变体:

class X {
    has $.value;

    method gist {
        '[' ~ $!value ~ ']'
    }
}

my $x = X.new(value => 42);

say $x; # [42]
$x.say; # [42]

当你调用 say 时,该程序在方括号中打印一个数字:[42]

请注意,双引号字符串中的插值使用 Str,而不是 gist。你可以在这里看到它:

say $x.Str; # X<140586830040512>
say "$x";   # X<140586830040512>

如果您需要自定义插值,请重新定义 Str 方法:

class X {
    has $.value;

    method gist {
        '[' ~ $!value ~ ']'
    }
    method Str {
        '"' ~ $!value ~ '"'
    }
}

my $x = X.new(value => 42);

say $x;     # [42]
$x.say;     # [42]

say $x.Str; # "42"
say "$x";   # "42"

现在,我们得到了期望的行为。

gist 
comments powered by Disqus