ruby - Ruby 中是否有用于反引号的替代语法?
问题描述
在 Ruby 中你可以做到a + b
,这相当于a.+(b)
.
您还可以+()
使用 覆盖该方法def +(other); end
。
反引号有替代语法吗?我知道这有效:
class Foo
def `(message)
puts '<' + message + '>'
end
def bar
`hello world`
end
end
Foo.new.bar # prints "<hello world>"
但这不起作用,例如
Foo.new.`hello world`
解决方案
.+
反引号和反引号没有区别
从上下文来看,message
是String
。所以使用引号。
class Foo
def `(message)
puts '<' + message + '>'
end
end
Foo.new.` 'hello world' #prints <hello world>
由于 codestyle 最好使用括号
Foo.new.`('hello world') #prints <hello world>
此代码在rb
-file 中完美运行。
有人可能会说它在irb
. 但irb
不是灵丹妙药(例如,如果您.
在行首使用,而不是在结尾使用)。因此,如果您想在 中使用它irb
,请将其称为
Foo.new.send(:`, 'hello world')