在Ruby中这种类似Haskell的理解实现中,我从未在Ruby中看到过一些代码:
class Array
def +@
# implementation
end
def -@
# implementation
end
end
Run Code Online (Sandbox Code Playgroud)
做什么def +@和def -@意味着什么?哪里可以找到关于他们的(半)官方信息?
tor*_*o2k 15
他们是一元+和-方法.当你写-object或时,它们被调用+object.+x例如,语法将替换为x.+@.
考虑一下:
class Foo
def +(other_foo)
puts 'binary +'
end
def +@
puts 'unary +'
end
end
f = Foo.new
g = Foo.new
+ f
# unary +
f + g
# binary +
f + (+ g)
# unary +
# binary +
Run Code Online (Sandbox Code Playgroud)
另一个不太做作的例子:
class Array
def -@
map(&:-@)
end
end
- [1, 2, -3]
# => [-1, -2, 3]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |