gpt4 book ai didi

ruby - {}之间是什么?

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

有一段代码:

 def test_sub_is_like_find_and_replace
assert_equal "one t-three", "one two-three".sub(/(t\w*)/) { $1[0, 1] }
end

我发现很难理解 { } 大括号之间的内容。谁能解释一下?

最佳答案

{...} 是一个 block 。 Ruby 会将匹配的值传递给 block ,并将 block 的返回值替换回字符串中。 String#sub文档更全面地解释了这一点:

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

编辑:根据 Michael 的评论,如果您对 $1[0, 1] 感到困惑,这只是获取第一次捕获 ($1) 并获取一个子字符串它的(特别是第一个字符)。 $1 是一个全局变量,设置为正则表达式后第一次捕获的内容(以真正的 Perl 方式),并且由于它是一个字符串,所以 #[] 运算符用于获取它的子字符串开始在索引 0 处,长度为 1。

关于ruby - {}之间是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16742965/

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