How to reduce this ruby code?
This is the code:
def explaination_exists
explaination_exists_flag = false
if self.explanation1.length > 5
explaination_exists_flag = true
end
if self.explanation2.length > 5
explaination_exists_flag = true
end
if self.explanation3.length > 5
explaination_exists_flag = true
end
if self.explanation4.length > 5
explaination_exists_flag = true
end
unless explaination_exists_flag
errors.add(:base, 'Atleast one explanation should be there.')
end
end
I want to reduce the code to a single line code, since there is no change
except for explaination[number].
I have tried this:
def explaination_exists
explaination_exists_flag = false
(1..4).each do |i|
if self."explanation#{i}".to_sym.length > 5
explaination_exists_flag = true
break
end
end
unless explaination_exists_flag
errors.add(:base, 'Atleast one explanation should be there.')
end
end
I know this is silly but can you suggest me some alteration that might work.
Thanks!
No comments:
Post a Comment