这是代码:
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
我想将代码简化为单行代码,因为除了说明[编号]之外没有任何变化。
我试过这个:
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
我知道这很愚蠢,但你能建议我一些可能有效的改变吗?
谢谢!