Reputation: 2125
How can I make this clearer and more concise?
def right_menu_link(name, url, css_class = nil)
css_class += " arrow" if css_class
css_class = "arrow" unless css_class
# ... rest of code
end
I've come up with at least this:
def right_menu_link(name, url, css_class = nil)
css_class ||= []; css_class << " arrow"
# ... rest of code
end
Upvotes: 0
Views: 167
Reputation: 3997
def right_menu_link(name, url, css_class = nil)
css_class = [*css_class] << ' arrow'
end
Always good to know your splats. Also, you're avoiding a conditional, compared to using a ternary operator.
EDIT As was pointed out, ruby versions < 1.9 leave the nil in the array. Newer versions ignore the nil, as was intended in the example.
Upvotes: 1
Reputation: 2380
I know its not so cool, since it will work only in valid cases, i.e. on missing argument or on array provided.
def right_menu_link(name, url, css_class = [])
css_class << ' arrow'
end
Upvotes: 0
Reputation: 14874
Use a ternary operator
css_class = css_class ? " arrow" : css_class + " arrow"
Upvotes: 1
Reputation: 115511
This will do the trick:
css_class = css_class ? "arrow" : css_class + " arrow"
It's known as ternary operation.
Upvotes: 1