Created
August 17, 2011 19:24
-
-
Save cowboy/1152377 to your computer and use it in GitHub Desktop.
An example using "yield self if block_given?"
This file contains 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
This explanation is amazing!! I have been looking for a good explanation for yield self if block_given? , and after I read through this example, I finally truly understand!! Thank you so much