Created
October 17, 2012 20:21
-
-
Save jvenator/3907908 to your computer and use it in GitHub Desktop.
10_17_12 - song_library.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def assert_equal(actual, expected) | |
| if expected == actual | |
| puts 'pass' | |
| else | |
| puts "fail: expected #{expected}, got #{actual}" | |
| end | |
| end | |
| def assert(statement) | |
| if statement | |
| puts 'pass' | |
| else | |
| puts "fail: expected #{statement} to be true." | |
| end | |
| end | |
| class Song | |
| attr_accessor :name | |
| # the following is what attr_accessor does for you - it creates your setter and getter methods | |
| # | |
| # def name=(string) | |
| # # store the string as the 'name' of the song | |
| # @name = string | |
| # end | |
| # def name | |
| # @name | |
| # end | |
| def initialize(name) | |
| @name = name | |
| end | |
| end | |
| class Library | |
| attr_accessor :songs | |
| def initialize | |
| end | |
| end | |
| # define a two classes, Songs, which have names, and a Library, which has many songs. | |
| # Songs should be able to be initialized with a name. | |
| begin | |
| assert_equal Song.new("Call Me Maybe").name, "Call Me Maybe" | |
| rescue => e | |
| puts e | |
| end | |
| # # Add each of the following to a Library as Songs | |
| song_names = [ | |
| "Call Me Maybe", | |
| "Hit Me Baby One More Time", | |
| "Poker Face", | |
| "Call On Me" | |
| ] | |
| # | |
| begin | |
| songs = song_names.collect{|s| Song.new(s)} | |
| library = Library.new | |
| library.songs = songs | |
| assert_equal library.songs, songs | |
| rescue => e | |
| puts e | |
| end | |
| # | |
| # define a find_songs Method that will find a song by name. | |
| # define a search_songs method that will search for a song that starts | |
| # with the same 4 letters. | |
| def find_songs(library, name_str) | |
| library.songs.select{|song| song.name == name_str } | |
| end | |
| def search_songs(library, string) | |
| library.songs.select{|song| song.name.match(string)} | |
| end | |
| begin | |
| assert_equal find_songs(library, "Poker Face").first.name, "Poker Face" | |
| rescue => e | |
| puts e | |
| end | |
| begin | |
| assert_equal search_songs(library, "Call").length, 2 | |
| assert_equal search_songs(library, "Call").first.name, "Call Me Maybe" | |
| rescue => e | |
| puts e | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment