Reputation: 4032
I have a helper method:
def get_str(exam)
@value = ""
if exam.is_mc
@value << "MC, "
end
if exam.is_ms
@value << "MS, "
end
if exam.is_ng
@value << "NG"
end
return @value
end
When all the three conditions are satisfied I get a string: MC, MS, NG
But if only first condition is satisfied I get the string: MC,
I don't want to show the comma in that case.
How is it possible?
Upvotes: 0
Views: 65
Reputation: 8247
This will work too:
def get_str(exam)
['MC', 'MS', 'NG'].select{|i| exam.send("is_#{i.downcase}").join(', ')
end
Only real advantage is that it will be easier to add more strings patterns.
Upvotes: 0
Reputation: 121010
The easiest way is to pass the concatenation duties to Array#join
.
def get_str(exam)
@value = []
@value << "MC" if exam.is_mc
@value << "MS" if exam.is_ms
@value << "NG" if exam.is_ng
@value = @value.join ', '
end
Hope it helps.
Upvotes: 4