cours0708/P5B/ruby/exercices/class_Carre.rb

56 lines
678 B
Ruby
Raw Permalink Normal View History

2008-11-25 21:11:16 +00:00
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
def carre(n)
n.premiers_impairs.somme
end
3.premiers_impairs.each do | i |
puts i.to_s
end
puts "Somme : #{3.premiers_impairs.somme}"
puts "Produit : #{3.premiers_impairs.produit}"
puts "Carré de 3 : #{carre(3)}"