Last active
April 7, 2019 22:09
-
-
Save jeromedalbert/5382169 to your computer and use it in GitHub Desktop.
Different ways to return in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Return statements are useless in snippets below, but they can help readability (highlight "end cases" of recursion) | |
# Order of preference : 3, 2/1, 4 | |
# 1) Extra returns make it more obvious what is happening. Maybe a bit verbose | |
def decompose(n) | |
if n == 0 | |
return [] | |
elsif n == 1 | |
return [1] | |
else | |
return [n + n-1 + n-1 + n-2] + decompose(n-2) | |
end | |
end | |
# 2) Not bad | |
def decompose(n) | |
if n == 0 | |
[] | |
elsif n == 1 | |
[1] | |
else | |
[n + n-1 + n-1 + n-2] + decompose(n-2) | |
end | |
end | |
# 3) Nice | |
def decompose(n) | |
return [] if n == 0 | |
return [1] if n == 1 | |
[n + n-1 + n-1 + n-2] + decompose(n-2) | |
end | |
# 4) Not very readable here | |
def decompose(n) | |
case n | |
when 0 | |
[] | |
when 1 | |
[1] | |
else | |
[n + n-1 + n-1 + n-2] + decompose(n-2) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how about
when {X} then {return_value}
for the case statement, i find that much more readable sort of likereturn [] if n == 0