3 m read

Understanding Methods in Ruby

Welcome to the next installment of our Ruby programming tutorial. After discussing loops in our previous article, we will now delve into understanding Ruby’s methods.

Method Creation and Usage

Ruby methods are defined with the def keyword followed by the method name and possible parameters. They are used to encapsulate reusable code. Here’s an example:

def hello_world
  puts 'Hello, world!'
end

hello_world # This calls the method, outputting "Hello, world!" to the console.
Code language: Ruby (ruby)

This method, when called, will print ‘Hello, world!’ to the console.

After Method Creation – Binding and Unbinding

Ruby methods can be unbound from one object and subsequently bound to another, a powerful feature allowing for a high degree of flexibility and reusability.

However, this process is not without its caveats – if the wrong number of parameters is passed to the proc, an error is generated, which emphasizes the importance of the methods’ correct usage.

class Greeter
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello, #{@name}!"
  end
end

alice = Greeter.new("Alice")
bob = Greeter.new("Bob")

# Binding and unbinding methods is more advanced and typically involves the Method and UnboundMethod classes.
Code language: Ruby (ruby)

Managing Parameters in Methods

Ruby methods can adjust to different numbers of arguments. If you use a lambda (a kind of function in Ruby) and give it more arguments than it expects, Ruby won’t complain; it just ignores the extras. But if you don’t give enough arguments, Ruby fills in the gaps with nil, which means “nothing” or “empty”.

# Define a lambda that expects 2 arguments
my_lambda = lambda do |a, b|
  puts "First argument: #{a.inspect}, second argument: #{b.inspect}"
end

# Call the lambda with exactly 2 arguments
my_lambda.call(1, 2)
# Output: First argument: 1, second argument: 2

# Call the lambda with 3 arguments (1 extra)
my_lambda.call(1, 2, 3)
# Ruby ignores the extra argument and outputs: First argument: 1, second argument: 2

# Call the lambda with only 1 argument (1 missing)
my_lambda.call(1)
# Ruby fills in the missing argument with nil and outputs: First argument: 1, second argument: nil

Code language: Ruby (ruby)

Sometimes, you might want to split a method that needs several arguments into simpler steps, especially if it’s not clear from the start how many arguments you’ll have. Ruby lets you do this by telling the method how many arguments to expect ahead of time. This setup helps avoid surprises and makes your code more predictable:

# Define a method that takes three arguments
def multiply(a, b, c)
  a * b * c
end

# Convert the method into a Proc object
method_proc = method(:multiply).to_proc

# Curry the Proc object, specifying it should expect 3 arguments
curried_proc = method_proc.curry(3)

# Now you can call the curried Proc in steps
step1 = curried_proc.call(2)    # Returns a Proc waiting for the next argument
step2 = step1.call(3)           # Returns a Proc waiting for the last argument
result = step2.call(4)          # Now performs the multiplication and returns 24

puts result  # Outputs: 24
Code language: Ruby (ruby)

Return Values

By default, all methods in Ruby return a value. This returned value is the last statement’s value evaluated within the method, whether explicitly stated using a 'return' statement or the final statement in the method’s body.

def add(a, b)
  a + b # The sum of a and b is returned automatically
end

puts add(5, 3) # Outputs 8

Code language: Ruby (ruby)

The Visibility of Methods

Ruby provides mechanisms to control the visibility of defined methods within the class to enhance encapsulation and data hiding – vital principles in object-oriented programming.

Public Methods

In Ruby, by default, every method defined within the class definition is marked as a public method. That means these methods can be accessed from any part of the program.

class MyClass
  def public_method
    "This is a public method."
  end
end

Code language: Ruby (ruby)

Private Methods

Contrary to public methods, private methods are only accessible within the context of the current object. That is, they cannot be called with an explicit receiver.

class MyClass
  private

  def private_method
    "This is a private method."
  end
end

Code language: Ruby (ruby)

Method Visibility Alteration

Ruby allows you to alter the visibility of the methods using ‘public’ or ‘private’ to make methods public or private, respectively.

class MyClass
  def method1; end
  def method2; end

  private :method1
  public :method2
end

Code language: Ruby (ruby)

Dangerous Methods of Ruby

Understanding Ruby also means being aware of its ‘dangerous’ methods, which can alter the state of the object.

The UnDef Method

The 'undef' statement in Ruby, allows you to undefined a method, essentially removing its definition from the specific class. Use it with caution, as it can lead to unexpected behavior if used incorrectly.

class MyClass
  def method_to_remove; end

  undef method_to_remove
end

Code language: Ruby (ruby)

Alias Methods

The alias statement creates a new name for an existing method, maintaining the current definition, even when methods are overridden later on. Take note that aliases cannot be defined within the method body.

class Greeter
  def hello
    puts "Hello!"
  end

  alias :greet :hello
end

greeter = Greeter.new
greeter.greet # Outputs "Hello!"

Code language: Ruby (ruby)

Conclusion

Understanding Ruby methods and their various aspects – from creation and binding, parameter management, and control of visibility to dealing with alias and under methods – is instrumental in writing effective Ruby code.

Also, via using method calls appropriately, Ruby empowers you to write efficient and reusable codes, which is greatly beneficial, especially for projects within web development and software industries.

Benji

Leave a Reply