Created
January 19, 2013 10:25
-
-
Save benolee/4571825 to your computer and use it in GitHub Desktop.
assignment gotchas
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
| @counter = 0 | |
| def big_calculation | |
| @counter += 1 | |
| end | |
| private :big_calculation | |
| heading "before local variable assignment, with implicit receiver" | |
| item "big_calculation" | |
| puts big_calculation | |
| item "big_calculation" | |
| puts big_calculation | |
| item "big_calculation" | |
| puts big_calculation | |
| big_calculation = big_calculation | |
| heading "after local variable assignment" | |
| item "big_calculation" | |
| puts big_calculation.inspect | |
| item "big_calculation" | |
| puts big_calculation.inspect | |
| item "big_calculation" | |
| puts big_calculation.inspect | |
| heading "explicit receiver" | |
| item "self.big_calculation" | |
| begin | |
| self.big_calculation | |
| rescue => e | |
| puts "exception caught:" | |
| puts e.message, e.backtrace | |
| end | |
| heading "implicit receiver" | |
| item "big_calculation()" | |
| puts big_calculation() | |
| item "big_calculation()" | |
| puts big_calculation() | |
| item "big_calculation()" | |
| puts big_calculation() | |
| # helpers | |
| BEGIN { | |
| DATA.instance_eval { truncate pos.tap { reopen __FILE__, "a+" } } | |
| $stdout = DATA | |
| def heading str | |
| print "\n\n-----> #{str}\n" | |
| end | |
| def item str | |
| print "> #{str}\n#=> " | |
| end | |
| } | |
| __END__ | |
| -----> before local variable assignment, with implicit receiver | |
| > big_calculation | |
| #=> 1 | |
| > big_calculation | |
| #=> 2 | |
| > big_calculation | |
| #=> 3 | |
| -----> after local variable assignment | |
| > big_calculation | |
| #=> nil | |
| > big_calculation | |
| #=> nil | |
| > big_calculation | |
| #=> nil | |
| -----> explicit receiver | |
| > self.big_calculation | |
| #=> exception caught: | |
| private method `big_calculation' called for main:Object | |
| assignment.rb:28:in `<main>' | |
| -----> implicit receiver | |
| > big_calculation() | |
| #=> 4 | |
| > big_calculation() | |
| #=> 5 | |
| > big_calculation() | |
| #=> 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment