Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax
3.
Example
4.
Reference To Method
5.
Frequently Asked Questions
5.1.
What does a Ruby method do?
5.2.
In Ruby, how do you create a method?
5.3.
What distinguishes a Ruby class method from an instance method?
5.4.
What occurs when a method is called in Ruby?
5.5.
In Ruby, how do you pass by reference?
6.
Conclusion
Last Updated: Mar 27, 2024

Reference To a Method In Ruby

Author Mayank Goyal
0 upvote

Introduction

Before moving into the topic, let us first see the method and how we create one. In a program, you'll frequently have a section of code that needs to be run repeatedly. Most programming languages have a procedure that allows you to extract the common code to one location rather than repeatedly write the same piece of code. We refer to it as a method in Ruby. A method must first be defined with the reserved word def before it may be used. We name our method after the def. We utilize the reserved term end to signify the end of our method specification.

Must Recommended Topic, procedure call in compiler design

Syntax

def say
  # method body goes here
end

Example

Suppose we have a function:

puts "hello"
puts "hi"
puts "how are you."
puts "I'm fine"


Please take note of how frequently we repeated the puts. We want a single location where we can send the information we wish. To do that, let's write a method definition.

def say(words)
  puts words
end

say("hello")
say("hi")
say("how are you")
say("I'm fine")


This may appear absurd at first because we added more code rather than saving any lines of code. But for our application to be more adaptable, we've separated the logic behind printing out text.

By inputting the method's name and adding parameters, we call (or invoke) the method. You'll see that there is a (words) after say in the method specification. This is referred to as a parameter. You utilize parameters when you need access to data that isn't covered by a method specification but is present elsewhere. You do not need to declare any parameters if the described method does not require access to external data.

Reference To Method

An array of strings providing the names of each of the methods accessible to that object are returned by the Object#methods introspection method. Any of these names can be supplied to a method of an object to obtain a Method object matching that method of that object.

The specific object whose method you invoked is tied to a Method object. It is the same as calling the method on the object directly when using the method's Method#call method. How many arguments the method accepts is indicated by the Method#arity method. The same arguments supplied to the original method are passed to call, including block arguments.

A Method object may be kept in a variable and sent to other methods as an argument. To pass existing methods to callbacks and listeners, use the following:

class EventSpawner
 def initialize
 @listeners = []
 @state = 0
 end
 def subscribe(&listener)
 @listeners << listener
 end
 def change_state(new_state)
 @listeners.each { |l| l.call(@state, new_state) }
 @state = new_state
 end
end
class EventListener
 def hear(old_state, new_state)
 puts "Method triggered: state changed from #{old_state} " +
 "to #{new_state}."
 end
end
spawner = EventSpawner.new
spawner.subscribe do |old_state, new_state|
puts "Block triggered: state changed from #{old_state} to #{new_state}."
end
spawner.subscribe &EventListener.new.method(:hear)
spawner.change_state(4)
# Block triggered: state changed from 0 to 4.
# Method triggered: state changed from 0 to 4


Method not tied to a particular object cannot be referenced since the behavior of the call would be unpredictable. By calling the method in the class, you can obtain a reference to a class method. When we do this, the bound object is an instance of the class, which is the class itself. Here is an illustration of how to get references to a class method and an instance of the same class:

class Welcomer
def Welcomer.a_class_method
 return "Greetings from the Welcomer class."
end
def an_instance_method
 return "Salutations from a Welcomer object."
end
end
Welcomer.method("an_instance_method")
# NameError: undefined method 'an_instance_method' for class 'Class'
Welcomer.new.method("an_instance_method").call
# => "Salutations from a Welcomer object."
Welcomer.method("a_class_method").call
# => "Greetings from the Welcomer class."

Frequently Asked Questions

What does a Ruby method do?

A Ruby method is a collection of expressions that yields a result. With the aid of methods, one can divide their code into simple-to-use subroutines that can be called from different parts of their program. This is sometimes referred to as a function in other languages. A method may be defined alone or as a component of a class.

In Ruby, how do you create a method?

Lowercase letters should be used to start method names. Ruby may interpret a method name that starts with an uppercase letter as a constant and may erroneously parse the call if this happens. Before calling a method, it should be defined since, otherwise, Ruby will throw an exception for calling an undefined method.

What distinguishes a Ruby class method from an instance method?

A method in Ruby gives an Object functionality. While an instance method only functions for one class instance, a class method provides functionality to the entire class.

What occurs when a method is called in Ruby?

By inputting the method's name and adding parameters, we call (or invoke) the method. You'll see that there is a (words) after say in the method specification. This is referred to as a parameter. You utilize parameters when you need access to data that isn't covered by a method specification but is present elsewhere.

In Ruby, how do you pass by reference?

"Pass by object reference" is used in Ruby. Any object member may have new values set to them inside the function, and these modifications will remain when the function exits. When a new object is assigned to the variable within the function, the old object is no longer referenced by the variable.

Conclusion

In this article, we learned about methods in ruby and why we use them. Later, we also learned how to call methods by reference in ruby with the help of a few examples. That’s all from the article. I hope you all like it.

If you want to learn more, check out our articles on Object Marshalling in RubyTainting Objects in RubyCopying Objects In RubyHow To Invoke Global Functions In Ruby?, and Object References in Ruby.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning, Ninjas!

Live masterclass