Ruby 代码块

引用
Ruby代码块可以通过yield方法传递给被调用的方法

1 测试类
require 'book'
require 'booklist'

booklist = BookList.new()
b1 = Book.new("iPod","123")
b2 = Book.new("How Objects Work","2")
booklist.add(b1)
booklist[1]=b2
print booklist[0].title, "\n"
print booklist[1].title, "\n" 

booklist.each{|book|
	print book.title, "\n"
}

booklist.print2{|x, y|
	print x,"\n"
	print y,"\n"
}

booklist.each_title{|title|
	print title,"\n"
}

author_regexp = /2/
booklist.each{|book|
	if author_regexp =~ book.author
		print "book.title: ",book.title, "\n"
	end
}

booklist.find_by_author(/2/){|book|
	print book.title, "\n"
} 

p booklist.find_by_author(/2/)



2 操作类
require 'book'

class BookList  
	def initialize()
		@booklist = Array.new()
	end
	
	def add(book)
		@booklist.push(book)
	end
	
	
	def length()
		@booklist.length()
	end
	
	
	def []=(n,book)
		@booklist[n] = book
	end
	
	
	def [](n)
		@booklist[n]
	end
	
	
	def delete(book)
		@booklist.delete(book)
	end
	
	def each
		@booklist.each{|book|
			yield(book)
		}
	end
	
	def print2
		yield(1,2)
	end
	
	def each_title
		@booklist.each{|book|
			yield(book.title)
		}
	end
	
	def find_by_author(author_regexp)
		if block_given?
			@booklist.each{|book|
				if author_regexp =~ book.author
					yield(book)
				end
			}
		else 
		    result = []
		    @booklist.each{|book|
		    	if author_regexp =~ book.author
		    		result << book
		    	end
		    }
		    return result
		end
	end
	
end 


3. 实体类
class Book
	attr_accessor :title, :author, :genredef 
	
	def initialize(title, author, genre=nil)
		@title  = title
		@author = author
		@genredef = genre
	end
end
 

猜你喜欢

转载自caerun.iteye.com/blog/1769630