#!/usr/bin/env ruby # This code comes from http://ruby-it.org/pages/Funzioni+di+ordine+superiore # Check the page for copyright notice and explanations def doppio_3 6 end def doppio_4 8 end def doppio(num) num*2 end def cerca_promessi_sposi return promessi_sposi end def cerca_divina_commedia return divina_commedia end ... def cerca_per_titolo(titolo) for i in libri return i if i.titolo=titolo end end def cerca_per_ISBN(codice) for i in libri return i if i.isbn=codice end end ... def cerca_per(funzione_chiave) for i in libri return if funzione_chiave(i) end end >> lunga= proc do |x| ?> x.length > 5 >> end => # >> ?> numerica=proc do |linea| ?> /[0-9]/.match(linea) >> end => # >> puts File.new('esempio.txt').reject(&lunga).reject(&numerica) => nil >> puts File.new('esempio.txt').reject(&lunga).select(&numerica) la 3 => nil both= proc do |funz_a,funz_b| proc do |x| funz_a[x] and funz_b[x] end end lunga= proc do |x| x.length > 5 end numerica= proc do |linea| /[0-9]/.match(linea) end lung_num=both[lunga,numerica] puts File.new('esempio.txt').select(&lung_num) #nome matricola anno_di_nascita sesso Gabriele 09101234 1980 M Elena 12120987 1986 F Nicola 12543211 1985 M Filippo 98762211 1953 M # commenti che iniziano per # Lorenzo 62617171 1990 M Costanza 01919111 1970 F Silvia 12679012 1979 F #Silvia 12679012 1079 F # le nostre funzioncine di ordine superiore, le aggiungiamo come # metodi della classe Proc class Proc def not! proc do |x| not self[x] end end def and(fun_b) proc do |x| self[x] and fun_b[x] end end def or(fun_b) proc do |x| self[x] or fun_b[x] end end end is_comm = proc { |linea| linea[0].chr == '#' } is_M = proc { |lin| lin[-2].chr == 'M' } pre_1980 = proc { |lin| (lin.split[2]).to_i < 1980 } is_F = is_M.not! post_1980 = pre_1980.not! ok = is_F.and(pre_1980).or is_M.and(post_1980) puts File.new('dati.txt').reject(&is_comm).find_all(&ok) La versione imperativa sarebbe: res=[] f=File.new('dati.txt') for l in f do if not l[0].chr =='#' if l[-2].chr == 'M' if l.split[2].to_i>=1980 res.push(l) end else if l.split[2].to_i> 1980 res.push(l) end end end end f.close puts res