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
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
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.
If you want to return both arrays combine them in another array on the
last line: [arr, arr1] and you’ll get an array containing [[“Blue”,
“Yellow”], [“1”, “2”]]