LoginSignup
9
9

More than 5 years have passed since last update.

Rubyで配列に入っている数値の合計を出すメソッドを作る(spec付き)

Last updated at Posted at 2013-07-23

配列に入っている数字の合計を出したいときってあるよね。
こんな感じに

[1, 2, 3, 4, 5].sum
=> 15

というわけで、Arrayを拡張してsumメソッドを作成してみました。

文字列が入っていてもto_iやto_fをしてとにかく合計を出して欲しいし、Floatで結果欲しい時は指定すればFloatで返して欲しい。
例えば、

[1, 2, '3.2', 4, 5].sum(:f)
=> 15.2

となるように作りたい

というわけで作ったのが以下。

class Array
  def sum(opt = :i)
    mode = case opt.to_sym
             when :i then 'to_i'
             when :f then 'to_f'
             else 'to_i'
           end

    self.inject(0){|result, item| result + item.send(mode)}
  end
end

specも書いてみました。

describe Array do
  describe '#sum' do
    context 'with no arguments' do
      subject { array.sum }

      context 'if all elements are integer' do
        let(:array) { [1, 2, 3, 4, 5] }
        it { expect(subject).to eql 15 }
      end

      context 'if array contains string' do
        let(:array) { [1, 2, 3, '4', 5] }
        it { expect(subject).to eql 15 }
      end

      context 'if array contains nil' do
        let(:array) { [1, 2, 3, nil, 5] }
        it { expect(subject).to eql 11 }
      end
    end

    context 'if :f is given' do
      subject { array.sum(:f) }

      context 'if all elements are integer' do
        let(:array) { [1, 2, 3, 4, 5] }
        it { expect(subject).to eql 15.0 }
      end

      context 'if array contains string' do
        let(:array) { [1, 2, 3, '4.2', 5] }
        it { expect(subject).to eql 15.2 }
      end

      context 'if array contains string' do
        let(:array) { [1, 2, 3, nil, 5] }
        it { expect(subject).to eql 11.0 }
      end
    end
  end
end

実行結果

21:08:32 - INFO - Running: spec/lib/array_ext_spec.rb
......

Finished in 1.32 seconds
6 examples, 0 failures

出来たー

specはもっとこうしたら良いとかあったらどなたでも是非教えて欲しいです。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9