Ruby Methods
Ruby Methods
Section titled “Ruby Methods”Ruby methods are blocks of code that perform a specific task. They are similar to functions in other programming languages and are used to bundle one or more repeatable statements into a single unit, promoting code reusability and organization.
Method names should conventionally begin with a lowercase letter or an underscore. If a method name starts with an uppercase letter, Ruby might interpret it as a constant, leading to parsing errors.
Methods must be defined before they are called; otherwise, Ruby will raise a NoMethodError exception.
Syntax for Defining Methods
Section titled “Syntax for Defining Methods”def method_name(parameter1, parameter2, ...) # expressions (method body) # ...endA simple method without parameters:
#!/usr/bin/env rubydef greet puts "Hello, Ruby!"endA method with parameters:
#!/usr/bin/env rubydef personalize_greeting(name) puts "Hello, #{name}!"endDefault Parameter Values:
Section titled “Default Parameter Values:”You can set default values for parameters. These defaults are used if the method is called without providing arguments for those parameters.
#!/usr/bin/env rubydef greet_with_default(name = "World") puts "Hello, #{name}!"end
greet_with_default # Output: Hello, World!greet_with_default("Alice") # Output: Hello, Alice!Calling Methods
Section titled “Calling Methods”To call a method, simply use its name. If the method expects arguments, provide them.
#!/usr/bin/env rubydef say_hello puts "Hello!"end
def add(a, b) puts a + bend
# Calling methodssay_hello # Call without parentheses if no arguments
add(5, 3) # Call with argumentsadd 10, 20 # Parentheses are often optional if unambiguousIf a method requires a specific number of arguments, and you call it with a different number, Ruby will raise an ArgumentError.
Example with Default Values:
Section titled “Example with Default Values:”#!/usr/bin/env ruby
def favorite_languages(lang1 = "Ruby", lang2 = "Python") puts "My favorite programming language is #{lang1}." puts "My second favorite is #{lang2}."end
favorite_languages("JavaScript", "Go") # Uses provided argumentsputs "---"favorite_languages("Rust") # lang1 is "Rust", lang2 uses default "Python"puts "---"favorite_languages # Uses both default valuesThis will produce:
My favorite programming language is JavaScript.My second favorite is Go.---My favorite programming language is Rust.My second favorite is Python.---My favorite programming language is Ruby.My second favorite is Python.Return Values from Methods
Section titled “Return Values from Methods”Every method in Ruby implicitly returns the value of the last evaluated expression in its body.
#!/usr/bin/env rubydef simple_calculator(a, b) sum = a + b difference = a - b difference # This is the last evaluated expression, so it's returnedend
result = simple_calculator(10, 4)puts "Result (difference): #{result}" # Output: Result (difference): 6The return Statement
Section titled “The return Statement”The return statement can be used to explicitly exit a method and return one or more values. If return is used without an expression, it returns nil. If multiple expressions are provided, return yields an array containing these values.
Syntax:
Section titled “Syntax:”returnreturn expressionreturn expr1, expr2, expr3Example:
Section titled “Example:”#!/usr/bin/env rubydef get_coordinates x = 10 y = 20 z = 30 return x, y, z # Returns an array [10, 20, 30]end
def get_status(code) return "OK" if code == 200 return "Error" # Implicitly returns "Error" if code is not 200end
coords = get_coordinatesputs "Coordinates: #{coords.inspect}" # Output: Coordinates: [10, 20, 30]
status_ok = get_status(200)puts "Status for 200: #{status_ok}" # Output: Status for 200: OK
status_err = get_status(404)puts "Status for 404: #{status_err}" # Output: Status for 404: ErrorVariable Number of Parameters (Splat Operator)
Section titled “Variable Number of Parameters (Splat Operator)”Ruby allows methods to accept a variable number of arguments using the splat operator (*). When used in a method definition, * collects any remaining arguments into an array.
#!/usr/bin/env rubydef display_items(category, *items) puts "Category: #{category}" puts "Number of items: #{items.length}" items.each_with_index do |item, index| puts " Item #{index + 1}: #{item}" endend
display_items("Fruits", "Apple", "Banana", "Orange")puts "---"display_items("Colors", "Red", "Green")puts "---"display_items("Tools") # items will be an empty arrayThis produces:
Category: FruitsNumber of items: 3 Item 1: Apple Item 2: Banana Item 3: Orange---Category: ColorsNumber of items: 2 Item 1: Red Item 2: Green---Category: ToolsNumber of items: 0Keyword Arguments
Section titled “Keyword Arguments”Ruby methods can also accept keyword arguments, which are specified by name when calling the method. This can make method calls more readable, especially when there are many parameters or boolean flags.
#!/usr/bin/env rubydef create_user(name:, email:, admin: false, notify: true) puts "Creating user: #{name}" puts "Email: #{email}" puts "Admin: #{admin}" puts "Notify: #{notify}" # ... logic to create user ...end
create_user(name: "Alice", email: "alice@example.com")puts "---"create_user(name: "Bob", email: "bob@example.com", admin: true, notify: false)
# Using double splat (**) for arbitrary keyword argumentsdef process_options(user_id, **options) puts "Processing for user: #{user_id}" options.each do |key, value| puts " Option #{key}: #{value}" endend
process_options(101, theme: "dark", layout: "compact", show_help: true)Class Methods
Section titled “Class Methods”Class methods are methods defined on a class itself, rather than on instances of the class. They are often used for factory methods or utility functions related to the class.
You can define a class method by prefixing the method name with self. or the class name itself within the class definition.
#!/usr/bin/env rubyclass Utility # Instance method def instance_method puts "This is an instance method." end
# Class method using self. def self.class_method_one puts "This is class_method_one." end
# Class method using the class name def Utility.class_method_two puts "This is class_method_two." endend
# Call class methods directly on the classUtility.class_method_oneUtility.class_method_two
# To call an instance method, you need an instanceutil_instance = Utility.newutil_instance.instance_methodBy default, methods defined inside a class are public. Methods defined at the top level (outside any class or module) become private instance methods of the Object class.
Ruby alias and alias_method
Section titled “Ruby alias and alias_method”The alias keyword creates an alias for an existing method or global variable. Aliases cannot be defined within a method body. When a method is aliased, the alias refers to the method’s definition at that point, even if the original method is later overridden.
alias_method is a method (typically used within classes/modules) that achieves the same for methods, often preferred for its flexibility (e.g., it can take symbols or strings as arguments).
Syntax:
Section titled “Syntax:”alias new_method_name old_method_namealias new_global_variable_name old_global_variable_name
# Within a class/module:alias_method :new_method_name, :old_method_nameExample:
Section titled “Example:”#!/usr/bin/env rubyclass Greeter def welcome(name) "Hello, #{name}!" end
alias_method :greet, :welcome # Aliasing an instance methodend
my_greeter = Greeter.newputs my_greeter.welcome("Original")puts my_greeter.greet("Alias")
$global_var = "Initial Global"alias $gvar $global_var # Aliasing a global variableputs $gvarAliasing built-in numbered global variables like $1, $2 is prohibited. Overriding core global variables can lead to unexpected behavior.
Ruby undef and undef_method
Section titled “Ruby undef and undef_method”The undef keyword cancels the definition of a method, making it no longer callable. It cannot appear inside a method body.
undef_method is its method-based counterpart, typically used within classes/modules.
Syntax:
Section titled “Syntax:”undef method_name
# Within a class/module:undef_method :method_nameExample:
Section titled “Example:”#!/usr/bin/env rubyclass Calculator def add(a, b) a + b end
def subtract(a, b) a - b endend
calc = Calculator.newputs calc.add(5, 3) # Output: 8
class Calculator undef_method :add # Undefine the 'add' methodend
# calc.add(7, 2) # This would now raise a NoMethodErrorputs calc.subtract(10, 4) # Output: 6Using undef and alias can modify a class’s interface, potentially independently of its superclass. However, care must be taken as internal method calls within the class to self might break if methods are undefined.