1

I ran into this code snippet in a codeWars solution.

def invert(list)
  list.map(&:-@)
end

I've never seen the @ before in ruby. It looks like it lets you specify an operation on the iterator in a &: anonymous function call.

I'm trying to work on my ruby terminology. What is the @ called in Ruby and when was it introduced?

Stefan
  • 109,145
  • 14
  • 143
  • 218
xander-miller
  • 529
  • 5
  • 12

1 Answers1

0

Here's an example of how you can use it

[1,2].map(&:-@) #=> [-1, -2]
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48
  • 1
    I found my answer in the comments on codeWars. `-@` is actually a method on integer. If you call `1.methods` you can see it. The method inverts the value of the integer. – xander-miller Oct 23 '18 at 23:08
  • yes that was clearly explained in the link I commented on your question but this clearly illustrates a use case IMHO. – lacostenycoder Oct 23 '18 at 23:11
  • 2
    @xander-miller It is not specific to Integer, it is merely a syntax for defining unary operators, not just `-`. Think of a vector class, you would likely define unary negation, and they are not integers. It is just another method name, with some different syntax on how to clarify it from a binary operator. – ForeverZer0 Oct 23 '18 at 23:31