加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – “def @”和“def”是什么意思?

发布时间:2020-12-16 20:15:11 所属栏目:百科 来源:网络整理
导读:在这个 Haskell-like comprehensions implementation in Ruby中有一些我从未在Ruby中看到的代码: class Array def +@ # implementation end def -@ # implementation endend def @和def – @是什么意思?在哪里找到(半)官方信息? 解决方法 它们是一元和方
在这个 Haskell-like comprehensions implementation in Ruby中有一些我从未在Ruby中看到的代码:
class Array
  def +@
    # implementation
  end

  def -@
    # implementation
  end
end

def @和def – @是什么意思?在哪里找到(半)官方信息?

解决方法

它们是一元和方法.当你写 – 对象或对象时,它们被调用.例如,语法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 +

另一个比较少的例子:

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

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

他们被提到here,还有一篇关于如何定义它们的文章here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读