RubyMine 2017.3 Help

Extract Method

Basics

When the Extract Method refactoring is invoked, RubyMine analyses the selected block of code and detects variables that are the input for the selected code fragment and the variables that are output for it.

The detected output variable is used as a return value for the extracted function.

Examples

BeforeAfter
name = "RubyMine" puts "Hello world from #{name}"
name = "RubyMine" def greet name puts "Hello world from #{name}" end greet(name)
class Boo def foo a = 0 b = 1 c = 2 return a * b + c * 123 end end
class Boo def foo b = 1 a = 0 c = 2 return bar(a, b, c) end private def bar(a, b, c) return a * b + c * 123 end end

Extracting a method

To extract a method, follow these steps

  1. In the editor, select a block of code to be transformed into a method or a function.
  2. On the main menu or on the context menu of the selection, choose Refactor | Extract | Method or press Ctrl+Alt+M.
  3. In the Extract Method dialog box that opens, specify the name of the new function.
  4. Specify the visibility modifier for the new method.

    If the private or protected sections exist, then the newly generated method is added there. If they don't exist, they are generated (the public section is not used, see https://github.com/bbatsov/ruby-style-guide#consistent-classes).

  5. In the Parameters area, do the following:
    • Specify the variables to be passed as method parameters, by selecting/clearing the corresponding checkboxes.
    • Rename the desired parameters, by double-clicking the corresponding parameter lines and entering new names.
  6. Check the result in the Signature Preview pane and click OK to create the required function.

    The selected code fragment will be replaced with a function call.

Processing duplicates

Look at the sample below. Selected is the fragment 11+2, which is used twice:

BeforeAfter
class Bar def foo a = |selection starts here| 11 + 2 |selection ends here| b = 11 + 2 end end
class Bar def foo a = addition() b = addition() end private def addition 11+2 end end

If duplicate code fragments are encountered, RubyMine suggests to replace them with the calls to the extracted method:

rm extract method duplicates

After that the first occurrence is silently replaced; for the other occurrences the following dialog shows up:

rm extract method duplicates1

The resulting code is:

rm extract method duplicates2
Last modified: 4 April 2018

See Also