When Methods do not return

Methods may or may not return value. There is no rule that they must return the value. These kind of methods can be used to display some type of message.

When Methods do not return in ruby

Here is a method called prompt that displays a message that is passed to it. We can use this method to display short messages to abstract the code from main program. We call this method by passing “Hello, World\n” and it displays the message.

We get input from the user and store it in the variable value and we call the function prompt by passing the variable value to display the message entered by the user. This method does not return anything.

Method - Working with data structure

Another reason to use a method that doesn’t return a value is when you want to create a method that might have to return multiple values or when you have to operate on larger data structure within the method.

When Methods do not return in ruby

In this method, we have declared and initialized the array called grade. We have defined a method named points, which adds the value specified by the user to each element of the array. This method takes array and another variable.

arr.map! { |grade| grade+= grace }

This statement uses a method called map. Map method belongs to the class array. Map method takes each element out of the array and stores it in some variable, using that variable we can perform our desired operations.

Here, for every instance, it stores the element of the array in the variable grade and adds the value grace to it. For first iteration, 60 is stored in grade and the value of grace which is 5 (passed while calling function) is added to the element of the array grades. So, when we print the grades using each iterator, the value of the elements of grades array is displayed.

When Methods do not return in ruby