Ruby代码块

作者: wilsoncai 分类: ruby/rails 发布时间: 2018-01-12 16:55

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

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/)
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 
class Book
    attr_accessor :title, :author, :genredef 

    def initialize(title, author, genre=nil)
        @title  = title
        @author = author
        @genredef = genre
    end
end

发表评论

电子邮件地址不会被公开。 必填项已用*标注