While you can make the return into a one-liner, this is one of those cases where I think being a little more explicit and skimmable is worth it. This is certainly debatable, but after working on a lot of different teams with rubyists I think that if you go to a one line version there's a good chance that you (or another member of your team) may misinterpret the potential exit states when looking at the code later.
I'd suggest:
def ident_list(keys)
id = nil
ident_a_node = nil
## method hidden
return IdentifierListNode.new(id, ident_a_node) unless id.nil?
nil
end
or if you don't care about the difference between false/nil in this case, even better:
def ident_list(keys)
id = nil
ident_a_node = nil
## method hidden
return IdentifierListNode.new(id, ident_a_node) if id
nil
end
Pretty much everyone who has worked in ruby for a little while understands that a final value in a method is implicitly returned (i.e. this will return nil if no return beforehand) - and you can get that a glance. My experience is that lots of people who have worked with ruby for a long time still get tripped up by variations of && and less explicit conditional returns.
If you are determined to use a one-liner, I'd go with Ryan's answer, mostly because it's an idiom that is used fairly commonly and less likely to be confused:
def ident_list(keys)
id = nil
ident_a_node = nil
## method hidden
id && IdentifierListNode.new(id, ident_a_node)
end
One caveat to this approach is that you actually end up with three possible return states instead of two (the other options will only return nil or your new IdentifierListNode
):
- When id is nil, return value will be nil
- When id is false, return value will be false
- When id is anything else, return value will be your
IdentifierListNode
object