diff options
| author | mokha <mokha@cisco.com> | 2019-04-27 11:29:36 -0600 |
|---|---|---|
| committer | mokha <mokha@cisco.com> | 2019-04-27 11:29:36 -0600 |
| commit | bbb3fa3ac5ad2455aaccc73f2b91bddb61248212 (patch) | |
| tree | 5371e37f622de4bf947e995b888100b9d23469e3 | |
| parent | 5a1b27336434d31f60400e5f80552c9342bcd7f8 (diff) | |
collapse 2 loops into one.
| -rw-r--r-- | spec/practice/luhn_spec.rb | 9 |
1 files changed, 6 insertions, 3 deletions
diff --git a/spec/practice/luhn_spec.rb b/spec/practice/luhn_spec.rb index 54d933e..ca1f373 100644 --- a/spec/practice/luhn_spec.rb +++ b/spec/practice/luhn_spec.rb @@ -25,9 +25,12 @@ require "spec_helper" class Luhn def self.valid?(credit_card) - step_1 = credit_card.digits - step_2 = step_1.each_with_index.find_all { |digit, index| index.even? }.map { |digit, index| digit }.sum - step_3 = step_1.each_with_index.find_all { |digit, index| index.odd? }.map { |digit, index| digit }.reverse + x = credit_card.digits.each_with_index.inject(Hash.new { |hash, key| hash[key] = [] }) do |memo, (digit, index)| + index.even? ? memo[:odd].push(digit) : memo[:even].push(digit) + memo + end + step_2 = x[:odd].sum + step_3 = x[:even] step_4 = step_3.map { |x| x * 2 } step_5 = step_4.map { |x| x.digits.sum } step_6 = step_5.sum |
