-
-
Save joeeeeey/97d199ec90342be52b3121b4bb96087c to your computer and use it in GitHub Desktop.
Ruby An example using "yield self if block_given?"
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
| # No yielding | |
| class NormPerson | |
| attr_accessor :first, :last | |
| def initialize(first = nil, last = nil) | |
| @first = first | |
| @last = last | |
| end | |
| def hello | |
| puts "#{@first} #{@last} says hello!" | |
| end | |
| end | |
| # You could do it like this... | |
| ben = NormPerson.new("Ben", "Alman") | |
| ben.hello # Ben Alman says hello! | |
| # Or like this... | |
| ben = NormPerson.new | |
| ben.first = "Ben" | |
| ben.last = "Alman" | |
| ben.hello # Ben Alman says hello! | |
| # (Optional) yielding | |
| class YieldPerson | |
| attr_accessor :first, :last | |
| def initialize(first = nil, last = nil) | |
| @first = first | |
| @last = last | |
| yield self if block_given? | |
| end | |
| def hello | |
| puts "#{@first} #{@last} says hello!" | |
| end | |
| end | |
| # While both of the previous ways work, so does this... | |
| YieldPerson.new do |p| | |
| p.first = "Ben" | |
| p.last = "Alman" | |
| p.hello # Ben Alman says hello! | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment