Sunday, November 15, 2009

ruby - 'yield' method

Hi Guys,

Hope most of our ROR developers are using 'yield' method in the layout file. In ruby we are not using the yield method(called from any method). I have come across the 'yield' method, its very interesting to know about the use of that method.

We can use 'yield' method inside any ruby method to execute the code inside the block.

example-1:
class Sample
def check_yield
yield
yield
yield
end
end

in the class 'Sample', i have called the yield method three times inside the method.

obj = Sample.new()
obj.check_yield{puts "hi am in method block"}

Output:
hi am in method block
hi am in method block
hi am in method block

Now i have created an object for the class 'Sample', and called the method 'check_yield' with the block({ }). When i executed the method it prints the results for three times. Because we are calling the yield for three times, the call to yield method executes the code inside the block({puts "hi am in method block"}). That's it.

We can also use the yield method with params.

example-2:
class Sample
def even_nos_upto(param)
for i in 0..param
yield(i) if i%2 == 0
end
end
end

obj = Sample.new()
obj.even_nos_upto(10){|x| puts x}

Output:
0
2
4
6
8
10

In Array, we are using the method 'collect', 'each' to get each value of the array.

[1,2,3,4,5].collect{|x| puts x}

Inside the collect method in Array class, the yield method called to return each value.

class Array
def my_collect
for i in 0..(self.length-1)
value = self[i]
yield(value)
end
end
def collect_greater_than(limit)
for i in 0..(self.length-1)
value = self[i]
yield(value) if value > 5
end
end
end

[1,2,3,4,5,6,7].collect{|x| puts x} # default method collect
[1,2,3,4,5,6,7].my_collect{|x| puts x} # method my_collect
[1,2,3,4,5,6,7].collect_greater_than(5){|x| puts x} # collect with condition

Output:
1
2
3
4
5
6
7
1
2
3
4
5
6
7
6
7

In the above sample, the method 'collect' & 'my_collect' works like a same. And the method collect_greater_than bit different from the first one, it returns the values based on the condition we have used.

No comments:

Post a Comment