HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyModerate

Is there a more succinct way to write this Ruby function?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thismorewayfunctionwritesuccinctrubythere

Problem

Just for fun, I want to try to write this Ruby function more succinctly. I imagine it can be done, I'm just not knowledgeable enough with Ruby yet to know how. Any suggestions?

def tags
    return ['Cancelled'] if cancelled?
    tags = []
    tags << 'Filled' if filled?
    tags << 'In Progress' if in_progress?
    tags
  end

Solution

Functional approach:

def tags
  if cancelled?
    ["Cancelled"]
  else
    [("Filled" if filled?), ("In Progress" if in_progress?)].compact
  end
end


Ideas behind the snippet:

  • Don't perform imperative side-effects on arrays (unless performance is a problem, not the case here).



  • Use the pattern: array of "nilable" expressions + compact to build arrays with conditional elements.



  • Minimize the use of inline conditional statements, they make a function harder to understand. They are ok as guards (early exit of functions), but not here. Note that I do use inline ifs, but they are expressions, not statements; more orthodox -but also more verbose- would be (filled? ? "Filled" : nil).

Code Snippets

def tags
  if cancelled?
    ["Cancelled"]
  else
    [("Filled" if filled?), ("In Progress" if in_progress?)].compact
  end
end

Context

StackExchange Code Review Q#15660, answer score: 19

Revisions (0)

No revisions yet.