Methods and Block in ruby
Methods
A method is a reusable section of code written to perform a specific task in a program. Methods is uses to separate between one big chunk of code.
Methods are defined using the keyword def
(short for "def
ine"). Methods have three parts:
- The header, which includes the
def
keyword, the name of the method, and any arguments the method takes. - The body, which is the code block that describes the procedures the method carries out. The body is indented two spaces by convention (as with
for
,if
,elsif
, andelse
statements) - The method ends with the
end
keyword.
def hello
puts hello
end
Method with arguments
def method_1(a,b)
p a, b
end
method_1(1, 2)
Splat arguments are arguments preceded by a *
, which tells the program that the method can receive one or more arguments. Example
def method_1(*args)
p args
end
method_1(1, 2, 3)
Sometimes we don’t just want a method to print something to the console, but we actually want that method to hand us (or another method!) back a value. And return is optional in ruby. For that, we use return
.
def method_1(n)
return n * 2
end
output = method_1(6)
output += 2
puts output
How Blocks Differ from Methods
The block that we define will only be called once, and in the context of the array that we are iterating over. It appears just long enough to do some work then vanishes .
Example to capitalize using block and yield:-
def call_with_foo_and_bar
yield "foo"
endcall_with_foo_and_bar do |block_arg1|
puts block_arg1.capitalize
end
In Ruby, methods may receive a code block in order to perform arbitrary segments of code. When a method expects a block, it invokes it by calling the yield
function.In above example first is a method and second is a block
Similarly , we can define other blocks . For example using block and yield to result out each_with_index from array.
class ArrayIndexValue
attr_accessor :arr
def initializer
@arr = Array.new
end def each_with_index
for i in 0..arr.length
yield arr[i],i
end
end
endobj = ArrayIndexValue.new
obj.arr = [1,2,3,4,5]
obj.each_with_index {|j,i| puts "key:- #{i} && value:- #{j}"}