Skip to content

Instantly share code, notes, and snippets.

@jeromedalbert
Last active April 7, 2019 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeromedalbert/5382169 to your computer and use it in GitHub Desktop.
Save jeromedalbert/5382169 to your computer and use it in GitHub Desktop.
Different ways to return in Ruby
# 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
@brossetti1
Copy link

brossetti1 commented Apr 7, 2019

how about when {X} then {return_value} for the case statement, i find that much more readable sort of like return [] if n == 0

def decompose(n)
  case n
  when 0 then []
  when 1 then [1]
  else [n + n-1 + n-1 + n-2] + decompose(n-2)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment