gpt4 book ai didi

ruby - =~ 运算符的顺序重要吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:51 25 4
gpt4 key购买 nike

下面两个语句除了编码风格有区别吗?

/regex/=~ "some_string_with_regex"

"some_string_with_regex"=~/regex/

最佳答案

是的,有区别。正如在 http://www.ruby-doc.org/core/classes/Regexp.html#M001232 中提到的

If =~ is used with a regexp literal with named captures, captured strings (or nil) is assigned to local variables named by the capture names.

/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ "  x = y  "
p lhs #=> "x"
p rhs #=> "y"

...

The assignment is not occur if the regexp is placed at right hand side.

"  x = y  " =~ /(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/
p lhs, rhs # undefined local variable

String#~=

关于ruby - =~ 运算符的顺序重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7122714/

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