From: "Jesús Gabriel y Galán" Date: 2008-08-28T18:38:03+09:00 Subject: Re: dont def need return On Thu, Aug 28, 2008 at 11:30 AM, Sijo Kg wrote: > Hi > I was learing Ruby and have code like > Class TestClass > def getcolors > arr=["Blue","Yellow"] > arr1=["1","2"] > end > end > obj=TestClass.new > puts obj.getcolors > > And the result is 1 2 ..This looks some strange to me since > I have not notice in other languages And if arr1=["1","2"] is absent > then it puts Blue Yellow ..So dont we need return .I would like to know > what happens here actually What happens is that Ruby returns the result of the last expression. This is true for methods and also for blocks: def a "this is the last expression" end a() # => "this is the last expression" Another example: def a(bool) if bool "it was true !" else "it was false !" end a(true) # => "it was true !" a(false) # => "it was false !" So, the return keyword is not needed. Some people say that (ab)using this feature can make the code more confusing, specially if the method or block is complex with branches, etc, and that explicitly using "return" is better. For simple methods is usually good enough, though. > And another inteesing thing is if I write > return arr=["Blue","Yellow"] the result i get is Blue Yellow > If I give > return arr=["Blue","Yellow"] > return arr1=["1","2"] then also I get "Blue Yellow > Why? This is because "return" exits from the method, and so this line "return arr1=["1","2"]" is never executed. Jesus.