gpt4 book ai didi

ruby - Ruby 中是否有反引号的替代语法?

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

在 Ruby 中,您可以执行 a + b,这等同于 a.+(b)

您还可以使用 def +(other); 覆盖 +() 方法;结束

是否有反引号的替代语法?我知道这行得通:

class Foo
def `(message)
puts '<' + message + '>'
end

def bar
`hello world`
end
end

Foo.new.bar # prints "<hello world>"

但这行不通,例如

Foo.new.`hello world`

最佳答案

.+ 和反引号没有区别

从上下文来看,messageString。所以使用引号。

class Foo
def `(message)
puts '<' + message + '>'
end
end

Foo.new.` 'hello world' #prints <hello world>

由于代码风格优于use parentheses

Foo.new.`('hello world') #prints <hello world>

此代码在 rb 文件中完美运行。

有人可能会说它在 irb 中不起作用。但是 irb 不是 Elixir (例如,如果您在行首而不是末尾使用 . )。所以如果你想在irb中使用它,就把它命名为

Foo.new.send(:`, 'hello world')

关于ruby - Ruby 中是否有反引号的替代语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55277386/

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