Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. &:method_name / Method / method()

&:method_name / Method / method()

&:method_name is a shorthand notation that converts a Symbol to a Proc. method() retrieves a method as an object.

Syntax

# Use &:method_name to omit the block.
collection.map(&:method_name)
# Equivalent to the following:
collection.map { |element| element.method_name }

# Use method() to get a method object.
method_object = object.method(:method_name)

# Convert the method object to a Proc with & and pass it as a block.
collection.map(&method_object)

Method List

Syntax / MethodDescription
&:symbolCalls to_proc on the symbol and passes the resulting Proc as a block.
method(:name)Returns the named method of the receiver as a Method object.
to_procConverts a Symbol or Method to a Proc object.
respond_to?Checks whether an object has the specified method.

Sample Code

# Use &:method_name to write the block in shorthand.
words = ["hello", "world", "ruby"]
upcased = words.map(&:upcase)
puts upcased.inspect  # ["HELLO", "WORLD", "RUBY"]

# Works for integer conversion as well.
string_numbers = ["1", "2", "3", "4"]
integers = string_numbers.map(&:to_i)
puts integers.inspect  # [1, 2, 3, 4]

# Practical example: remove nil values.
mixed = ["apple", nil, "banana", nil, "cherry"]
fruits_only = mixed.select(&:itself)
puts fruits_only.inspect  # ["apple", "banana", "cherry"]

# Use method() to extract a method as an object.
def transform(text)
  text.upcase + "!"
end

transform_method = method(:transform)
puts transform_method.call("hello")  # HELLO!

# Pass a method() as a block using &.
words = ["hello", "world"]
puts words.map(&method(:transform)).inspect  # ["HELLO!", "WORLD!"]

Overview

&:method_name is one of the most commonly used shorthand notations in Ruby. Internally, Symbol#to_proc is called, generating a Proc equivalent to the block { |x| x.method_name }.

Using method(:name), you can treat a method as a first-class object, making it useful for callbacks and function composition. Methods that accept arguments cannot receive them via the &:method_name form, so use the regular block syntax when arguments are needed.

If you find any errors or copyright issues, please .