Being a Software Developer we are expected to work on new technology irrespective of language that we have previous work experience in. It's not a big deal as long as we are familiarised with the syntax of the new language.
I recently switched the job and was expected to work on ruby on rails.
I was working on a code and returning a value from a function and I don't see any error or warning in that until I used lint to check my code quality. It threw me the warning,
Redundant 'return' detected
I had no clue about this as I was sure that my code is fine. After intense googling, I found that by default ruby doesn't expect a function to return some value.
You can check the issue from this question in StackOverflow: https://stackoverflow.com/questions/1023146/is-it-good-style-to-explicitly-return-in-ruby
After modification my function looked something like this:
def some_function(x)
y = 33
unless x.blank?
y = if x == 3
10
elsif x == 5
16
else
nil
end
end
end
The Drive code:
x = ''
z = some_function(x)
print z
Even after modification my function didn't return the expected value. It was expected to return the y value as '33'
which is set by default once it enters the function.
It returned nil
instead of the expected output : '33'
I got confused and started debugging the code. Later I found out the problem.
The problem is, we should return the final variable in order for the function to return a value.
So instead of using 'return'
keyword we can simply use the variable name at the end like this:
def some_function(x)
y = 33
unless x.blank?
y = if x == 3
10
elsif x == 5
16
else
nil
end
end
y #change made here to return the final value of y
end
so that whatever the final value of the variable is, it will be returned and this solves the issue.
Top comments (1)
Good investigation!
Idiomatic Ruby often involves an "early return", so it is possible that the following style of code, which avoids a local variable, would also work for you.
An
if
orunless
at the end of a method can often be avoided in this way.