49 lines
599 B
Ruby
49 lines
599 B
Ruby
|
module Inject
|
||
|
def inject(val)
|
||
|
each do | element |
|
||
|
val = yield(val, element)
|
||
|
end
|
||
|
val
|
||
|
end
|
||
|
|
||
|
def somme
|
||
|
inject(0) do | s, element |
|
||
|
s + element
|
||
|
end
|
||
|
end
|
||
|
|
||
|
def produit
|
||
|
inject(1) do | p, element |
|
||
|
p * element
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
|
||
|
class Impairs
|
||
|
include Inject
|
||
|
def initialize(n)
|
||
|
@cardinal = n
|
||
|
end
|
||
|
|
||
|
def each
|
||
|
i = 1
|
||
|
@cardinal.times do
|
||
|
yield i
|
||
|
i = i +2
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
|
||
|
class Integer
|
||
|
def premiers_impairs
|
||
|
Impairs.new(self)
|
||
|
end
|
||
|
end
|
||
|
|
||
|
3.premiers_impairs.each do | i |
|
||
|
puts i.to_s
|
||
|
end
|
||
|
|
||
|
puts "Somme : #{3.premiers_impairs.somme}"
|
||
|
puts "Produit : #{3.premiers_impairs.produit}"
|