一段代码的重构 发表于 2017-12-19 | 第一次123456789101112131415161718def update_encourage_count! thanks = [[*0..2], [*1..5]] hugs = [[*0..3], [*1..5]] handclaps = [[*0..5], [*2..7]] if votes.exists? choiced_thanks = thanks[1] choiced_hugs = hugs[1] choiced_handclaps = handclaps[1] else choiced_thanks = thanks[0] choiced_hugs = hugs[0] choiced_handclaps = handclaps[0] end self.thanks_count = thanks_count.to_i + choiced_thanks.sample self.hugs_count = hugs_count.to_i + choiced_hugs.sample self.handclaps_count = handclaps_count.to_i + choiced_handclaps.sample save!end 第二次123456789101112def update_encourage_count! thanks = [[*0..2], [*1..5]] hugs = [[*0..3], [*1..5]] handclaps = [[*0..5], [*2..7]] choiced_thanks = votes.exists? ? thanks[1] : thanks[0] choiced_hugs = votes.exists? ? hugs[1] : hugs[0] choiced_handclaps = votes.exists? ? handclaps[1] : handclaps[0] self.thanks_count = thanks_count.to_i + choiced_thanks.sample self.hugs_count = hugs_count.to_i + choiced_hugs.sample self.handclaps_count = handclaps_count.to_i + choiced_handclaps.sample save!end 第三次1234567def update_encourage_count!(thanks = [[*0..2], [*1..5]], hugs = [[*0..3], [*1..5]], handclaps = [[*0..5], [*2..7]]) choiced_thanks, choiced_hugs, choiced_handclaps = votes.exists? ? [thanks[1], hugs[1], handclaps[1]] : [thanks[0], hugs[0], handclaps[0]] self.thanks_count = thanks_count.to_i + choiced_thanks.sample self.hugs_count = hugs_count.to_i + choiced_hugs.sample self.handclaps_count = handclaps_count.to_i + choiced_handclaps.sample save!end