From: Mike Gold Date: 2008-11-01T19:43:59+09:00 Subject: Re: Iterator objects and lazy evaluation Yuh-Ruey Chen wrote: > > I know that I could do this instead: > > ['file1', 'file2', 'file3'].each {|x| > open(x) { > # blah > } > } > > but sometimes it's inconvenient to do that if there's already a > function that accepts an Enumerable such as read_files above. some_file_operation = lambda { |file| puts "doing stuff with #{file}" } %w(file1 file2 file3).each(&some_file_operation) # => # doing stuff with file1 # doing stuff with file2 # doing stuff with file3 def some_file_operation2(file) puts "doing stuff with #{file}" end %w(file1 file2 file3).each(&method(:some_file_operation2)) # => # doing stuff with file1 # doing stuff with file2 # doing stuff with file3 In Ruby, a.x calls the method named 'x', whereas Python requires parens a.x(). As a consequence, the syntax for getting the method in Ruby is a.method(:x). > > 2) Is there some lazy evaluation library that can recalculate lazy > expression when values change? Something with the following semantics > (or something like it): > > x = lazy {a + b} > a = 1 > b = 2 > p x # 3 (calculates a + b) > p x # 3 (memoized value) > a = 3 > p x # 5 (recalculates a + b) > a = [1,2] > b = [3,4] > p x # [1,2,3,4] (recalculates a + b) > p x # [1,2,3,4] (memoized value) > a[1] = '.' > p x # [1,'.',3,4] (recalculates a + b) > > I know there's a library called lazy.rb, but it's not exactly what I'm > looking for as it doesn't implement this functionality. If you google for ruby memoization, you'll find several options available. However none can use the syntax in your example. Ruby determines at compile time that "p x" is a local variable lookup. You'll have to use "p lazy.x" or some such. -- Posted via http://www.ruby-forum.com/.