Skip to content

Four arithmetic operations #79

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/nyaplot/data.rb
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,16 @@ def label
@label
end

[:+, :-, :/, :*].each do |operator|
define_method(operator) do |obj|
if obj.is_a? Nyaplot::Series
Nyaplot::Series.new(label, (self.zip obj.to_a).map { |arr| arr.inject(&operator) })
elsif obj.is_a? Numeric
Nyaplot::Series.new(label, self.map { |e| e.send(operator, obj) })
end
end
end

def method_missing(meth, *args, &block)
if @arr.respond_to?(meth)
@arr.send(meth, *args, &block)
Expand Down
56 changes: 56 additions & 0 deletions spec/nyaplot/data_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,60 @@
expect(@series.size).to eq(@series.to_a.size)
end
end

context "#+" do
it "should add each element of the two Series" do
another_series = Nyaplot::Series.new('another_series', [20, 40])

expect((@series + another_series).to_a).to eq( [30, 70] )
end

it "should add the number to each element of the Series" do
number = 10

expect((@series + number).to_a).to eq( [20, 40] )
end
end

context "#-" do
it "should subtract the passed Series from the Series" do
another_series = Nyaplot::Series.new('another_series', [20, 40])

expect((@series - another_series).to_a).to eq( [-10, -10] )
end

it "should subtract the number from the Series" do
number = 10

expect((@series - number).to_a).to eq( [0, 20] )
end
end

context "#/" do
it "should divide each element of the Series by the each element of the passed Series" do
another_series = Nyaplot::Series.new('another_series', [20.to_f, 40.to_f])

expect((@series / another_series).to_a).to eq( [10/20.to_f, 30/40.to_f] )
end

it "should divide each element of the Series by the passed number" do
number = 10.to_f

expect((@series / number).to_a).to eq( [10/10.to_f, 30/10.to_f] )
end
end

context "#*" do
it "should multiply each element of the two Series together" do
another_series = Nyaplot::Series.new('another_series', [20, 40])

expect((@series * another_series).to_a).to eq( [200, 1200] )
end

it "should multiply each element of the Series by the number" do
number = 10

expect((@series * number).to_a).to eq( [100, 300] )
end
end
end