`def +@` 和 `def -@` 是什么意思? [英] What do `def +@` and `def -@` mean?

查看:61
本文介绍了`def +@` 和 `def -@` 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个 Ruby 中类似 Haskell 的推导式实现中有一些代码我从未在 Ruby 中见过:

In this Haskell-like comprehensions implementation in Ruby there's some code I've never seen in Ruby:

class Array
  def +@
    # implementation
  end

  def -@
    # implementation
  end
end

def +@def -@ 是什么意思?在哪里可以找到有关他们的(半)官方信息?

What do def +@ and def -@ mean? Where to find (semi-)official informations about them?

推荐答案

它们是一元 +- 方法.当您编写 -object+object 时会调用它们.例如,语法 +x 被替换为 x.+@.

They are unary + and - methods. They are called when you write -object or +object. The syntax +x, for example, is replaced with 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 +

另一个不那么做作的例子:

Another less contrived example:

class Array
  def -@
    map(&:-@)
  end
end

- [1, 2, -3]
# => [-1, -2, 3]

此处提到了它们,并且有一篇关于如何定义它们的文章此处.

They are mentioned here and there's an article about how to define them here.

这篇关于`def +@` 和 `def -@` 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆