# How &:method Shortcut Works in Ruby

*Published on October 13, 2022*

---


You probably know about Ruby's&nbsp;`&:method`&nbsp;shortcut.

Given a method name as a symbol prefixed with an&nbsp;`&`&nbsp;operator, Ruby calls that method on the argument.

In the example below, Ruby calls&nbsp;`length`&nbsp;on each item.

```ruby
items = [ 'hi', 'hello' ]
items.map(&:length) # [2, 5]

(1..3).map(&:to_s)  #=> ["1", "2", "3"]
```

Let's learn how this works.

## Behind the Scenes

When you prefix the&nbsp;`&`&nbsp;operator to a method argument, it calls&nbsp;`to_proc`&nbsp;on its operand, and passes the result as a block.

You can override the&nbsp;`to_proc`&nbsp;method to return a custom block, as the&nbsp;`Person`&nbsp;class does below.

```ruby
def bar(&block)
  block.call
end

class Person
  def self.to_proc
    -> { puts 'hello world' }
    # Proc.new { puts 'hello world' }
    # proc { puts 'hello world' }
  end
end

bar(&Person) # "hello world"
```

Now, let's override the&nbsp;`Symbol`&nbsp;class to add a&nbsp;`to_proc`&nbsp;method.

It will return a proc/lambda that calls the symbol (`self`) on its argument (`item`), using the&nbsp;`send`&nbsp;method.

```ruby
class Symbol
  def to_proc
    ->(item) { item.send self }
  end
end
```

Remember that all symbols (e.g.&nbsp;`:item`) are instances of&nbsp;`Symbol`. So you can call&nbsp;`to_proc`&nbsp;method on a symbol like&nbsp;`:item.to_proc`.

Now, when you pass&nbsp;`&:some_method`&nbsp;to a method that accepts a proc, it calls&nbsp;`some_method`&nbsp;on the argument.

The two calls below are equivalent.

```ruby
items = [ 'hi', 'hello' ]

items.map(&:length) # [2, 5]
items.map { |item| item.send :length } # [2, 5]
```

The good news is, we don't have to monkey-patch&nbsp;`Symbol`&nbsp;to add this method. Ruby already does this. This shortcut was added in ActiveSupport and became&nbsp;[official](https://ruby-doc.org/core-3.1.1/Symbol.html#method-i-to_proc)&nbsp;in Ruby 1.8.7.

Pretty nice, right? Let me know in the comments below what you think.

—

I hope you liked this article and you learned something new. I sure did. If you have any questions or feedback, please&nbsp;[send me an email](mailto:akshay.khot@hey.com). I look forward to hearing from you.

If you liked this post and would like to receive future posts directly by email, please subscribe below.

You might also enjoy these articles:

- [A brief introduction to Rack](/definitive-guide-to-rack)
- [Understanding Authenticity Tokens in Rails](/how-rails-authenticity-tokens-protect-against-csrf)
- [Building a to-do list using Hotwire](/building-to-do-list-using-hotwire-and-stimulus)
- [Concerns in Rails: Everything You Need to Know](/how-rails-concerns-work-and-how-to-use-them)

