Created
October 5, 2013 13:07
-
-
Save cnocon/6840757 to your computer and use it in GitHub Desktop.
Grandfather clock exercise from "Learn to Program" by Chris Pine.
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
| # Grandfather clock. | |
| # Write a method that takes a block and calls it once for each hour that has passed today. | |
| # That way, if I were to pass in the block: | |
| # do | |
| # puts 'DONG!' | |
| # end | |
| # it would chime (sort of) like a grandfather clock. Test your method out with a few different blocks. | |
| # Hint: You can use Time.new.hour to get the current hour. | |
| # However, this returns a number between 0 and 23, so you | |
| # will have to alter those numbers in order to get ordinary | |
| # clock-face numbers (1 to 12). | |
| # logic: find the number of hours passed, then do the block that number of times | |
| def clockwork &block | |
| current_hour = Time.new.hour | |
| if current_hour > 12 | |
| current_hour = current_hour - 12 | |
| end | |
| if current_hour == 0 | |
| current_hour = 12 | |
| end | |
| current_hour.times do | |
| block.call #I forgot to put this in the method the first time | |
| end | |
| end | |
| # worked: | |
| clockwork do | |
| puts "Chime!" | |
| end | |
| # didn't work; you can't access the method's variables within the block? would i need to create a class? | |
| # clockwork do | |
| # puts "#{current_hour}" | |
| # end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment