dont def need return

S

Sijo Kg

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

Why?
Thanks in advance
Sijo
 
C

Codeblogger

[Note: parts of this message were removed to make it a legal post.]

Hi,

Ruby implicitly returns the last value of a code block unless you explicitly
use return. In the last case it works as expected in all other languages.

Kind regards

Nicolai
 
J

Jesús Gabriel y Galán

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.
 
T

Thomas Wieczorek

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

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"]]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top